Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to run a cron command only once a day but not at a specific time as the times my computer is on are unpredictable.

Can I do it?

share|improve this question
Please remember to include your OS, different systems have different cron implementations. – terdon Jul 3 '13 at 20:39
up vote 3 down vote accepted

Depending on your cron implementation you may be able to use @daily. From man cron:

Instead of the first five fields, one of eight special strings may

       string          meaning
       ------          -------
       @reboot         Run once, at startup.
       @yearly         Run once a year, "0 0 1 1 *".
       @annually       (same as @yearly)
       @monthly        Run once a month, "0 0 1 * *".
       @weekly         Run once a week, "0 0 * * 0".
       @daily          Run once a day, "0 0 * * *".
       @midnight       (same as @daily)
       @hourly         Run once an hour, "0 * * * *".

I'm not sure how cron will deal with @daily if your computer is off at midnight. Perhaps it will run the job next time it is turned on, but I doubt it. Apparently, anacron can do this but I have never used it. Another solution would be to have your job create a file every time it is run and then write a script that checks the modification date of the file and runs the job again if it is more than a day old. For example:

#!/usr/bin/env bash

## The command you want to run, change this to whatever
## command you actually want.
COMMAND='echo foo';

## Define the log file

## If the log file doesn't exist, run your command
if [ ! -f $LOGFILE ]; then
    ## If the command succeeds, update the log file
    $COMMAND && touch $LOGFILE
    ## If the file does exist, check its age
    AGE=$(stat -c "%Y" $LOGFILE);
    ## Get the current time
    DATE=$(date +%s);
    ## If the file is more than 24h old, run the command again
    if [[ $((DATE - AGE)) -gt 86400 ]]; then
      $COMMAND && touch $LOGFILE;

If you then make a crontab that runs the script every hour (@hourly), it will run your command every time 24 hours have passed since the last time it ran.

share|improve this answer
What if my computer is off at midnight? – Ricardo Jul 3 '13 at 20:44
@Ricardo good point, I updated my answer with an alternate solution. – terdon Jul 4 '13 at 0:21

anacron does this. Just set the time that you want, and if your computer happens to be off during that time, it will start as soon as the computer turns back on.

share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .