Wednesday, March 20, 2013

CronJob for nightly backup

To add a cronjob you edit the cron file via the crontab command, which basically opens/creates a file for you in vi. The format is five values indicating the frequency of when it should run and the command to run. Each user has their own crontab and the commands are run as that user.

Open your cronjob file for editing in vi.

crontab -e

Schedule a script to run on the 2nd minute of the 1st hour of each day. I.e. 1:02am each night.

2 1 * * * /whatever/go.sh

Your Mac is basically linux and the above will work, but if the schedule comes due while your OSX Lion is asleep, the cronjob will be skipped. To avoid the sleeping Mac problem, you can use pmset to schedule a wakeup window.

Tell your Mac to wake up at 1:00am each night and go back to sleep five minutes later.

sudo pmset repeat wake MTWRFSU 01:00:00 sleep MTWRFSU 01:05:00

See what you've done.

$ pmset -g sched
Repeating power events:
  wake at 1:00AM every day
  sleep at 1:05AM every day

I found that to not work so great. It seems that the natural "go to sleep when inactive" would kick in prior to the scheduled sleep then next time you open the mac it says "hey, I'm just about to go to sleep, are you sure". So a better alternative is to just wake at the specified time.

sudo pmset repeat cancel
sudo pmset repeat wake MTWRFSU 01:00:00
pmset -g sched
{ "loggedin": false, "owner": false, "avatar": "", "render": "nothing", "trackingID": "UA-36983794-1", "description": "How to use crontab to schedule nightly backups. Also chron job chrontab for the spelling impared.", "page": { "blogIds": [ 74 ] }, "domain": "holtstrom.com", "base": "\/michael", "url": "https:\/\/holtstrom.com\/michael\/", "frameworkFiles": "https:\/\/holtstrom.com\/michael\/_framework\/_files.4\/", "commonFiles": "https:\/\/holtstrom.com\/michael\/_common\/_files.3\/", "mediaFiles": "https:\/\/holtstrom.com\/michael\/media\/_files.3\/", "tmdbUrl": "http:\/\/www.themoviedb.org\/", "tmdbPoster": "http:\/\/image.tmdb.org\/t\/p\/w342" }