Script for automated backup of a notebook

Hey Guys,

Last evening Mathematica crashed and hours of work were gone, because I forgot to save my notebook. During homework today, I just pressed Ctrl+S every few minutes, to make sure that I don’t loose my progress again. However, after a few more hours, I discovered that my first approach to the problem has been much better. Sadly, I’ve overwritten my notebook every time with Ctrl+S, so my calculations from the morning were also gone.

So I decided to look for an auto-save function for Mathematica. At a coding internship, I once used some software, to track down all changes and create a nice version history, which led me swap between different versions of my code easily. Unfortunately, I was not able to find something like this for Mathematica (if you know an existing method, please tell me!). Thus I thought I could try to write a code to autosave my progress every 10 minutes into a new file.

Basically the code can be used inside every .nb file. It creates a new directory in the notebook-directory with the name "filename_versions.. Every time you execute the code it looks up the current time and exports the notebook into the versions directory with the name filename_yyyy_mm_dd_hh_mm.nb. However, only a new version is created if the last backup-file is older than x minutes (I used 10 minutes for x).

I tried out the code a few times (I simply copied the code to the top of my homework Mathematica notebook). Since I often use Ctrl+A Shift+Enter to evaluate all cells at once I also execute the autosave every time. The result was pretty nice, I had a nice history of my progress in the versions-directory and was able to look up old stuff I deleted in my code.

I want to point out, that I am a beginner at Mathematica, so if you have any suggestions how I could improve my code please tell me (It’s not the most beautiful code, but it works.). I already thought of putting the code into a package, but first I want to try it out more often.

I’m looking forward to hear your opinion on this problem and my approach to solve it.

Best regards,
Tobias

Here is another snippet which saves all open notebooks on a regular time interval.
The best place for it is your init.m file.

  1. Use Notebooks[] to get a list of currently open notebooks.

  2. Use Extract to filter (hgo) the ones we want ( every notebook except the Messages WIndow)

  3. Use NotebookSave /@ to save them

  4. Use SessionSubmit to cause this to happen at a given interval

    Off[Rule::argr]; (* Suppress an annoying message. A better way would be a more specific filter *)

    savePeriod=Quantity[300,“Seconds”];

    obj=ScheduledTask[
    hgo[aza_] :=And[ aza[“DocumentType”]==“Notebook” , aza[“WindowTitle”]!=“Messages”] ;

    NotebookSave/@ Extract[Notebooks,Position[ Association/@NotebookInformation /@Notebooks,_?hgo] ] ,savePeriod]//SessionSubmit ;

1 Like

Some more ideas.

Preferences setting.

From MSE, this, and this.