Search code examples
bashcronexpr

Is it possible to set a cron job or bash script to run X minutes from now?


I understand I can set a cron job to run every 5 minutes with crontab -e by adding a line such as: */5 * * * * /path/to/script.sh.

Is it possible to get the system time in minutes using date +"%M" for example, and then set a cron job to run at date +"%M" plus 5 minutes?

I know I can get date +"%M" + 5 via the following process:

$ MIN=`date +"%M"`
$ export MIN
$ expr $MIN + 5

Is it possible to use this to set a cron job or script to run at "current time in minutes" plus "X minutes"?

I could imagine this being useful in an application in which a user creates a new document and then is prompted to save or title the document X minutes after creating it.


Solution

  • You should use the at command instead.

    With at, you can specify the time when a command should be run using time or even keywords like midnight, teatime, tomorrow etc..

    You can specify the time after 5 min like this:

    at now + 5 min
    

    And then enter the command you want to schedule. Or you can enter your scheduled jobs in a jobs file and give it as a argument for the at command using the -f option.

    Sample of a jobs file:

    $ cat myjobs.txt
    /path/to/a/shell-script.sh
    /path/to/any/command/or/script.sh
    

    The following command will execute those jobs after 5 mins:

    $ at -f myjobs.txt now + 5 min
    

    Check this link for more information.