2.11.10. Non-standard cron tasks

As part of cron tasks, it is impossible to implement any non-standard interval or with an indication of waiting for the execution of another command. By itself, crontab can use the schedule only with an accuracy of the minute, and you cannot specify a certain number of seconds. Also, tasks cannot be launched in order of execution, that is, waiting for the previous task to finish and then launch the next one. To implement this, you can use useful bash features.

To run two commands sequentially, you must specify both commands in the task, separating them with the symbol ;... Such an indication will work as a sequence of commands of the form:

command1 ; command2 ; ... ; commandn

The next command will execute anyway, even if the previous one returned an error.

If you need to check for an error or the successful execution of the previous command, then you can use the following divisors:

  • && — execute the next command only if the previous one was completed successfully.
  • || — execute the next command only if the previous not was successful and returned an error.

An example of use is as follows:

command1 ; command2 && command3 || command4

The commands will be executed in the following order and conditions: command1 and command2 will be executed anyway, but command3 will be executed only if command2 completed without errors. command4 will only be executed if when executing command3 an error will be returned.

Important points:

  • cron tasks are not started at the very beginning of a minute, quite often a task can be launched in the first seconds of a minute or later, and therefore it is problematic to specify the exact start time.
  • Do not set too high a value for waiting, since the command execution time is limited, within the framework of shared hosting the maximum execution time of the process is 1 hour, for business hosting this value is 4 hours.
  • It is strongly discouraged to use tasks with an extremely small start interval, as this is fraught with excessive consumption of server resources, and is also a violation terms of service p. 5.8.

As mentioned earlier, crontab does not have the ability to customize execution exactly to the second, and therefore you have to resort to various tricks, for example, specifying the sequential execution of several commands using the wait command. For example, the following command will run 30 seconds after it is executed:

sleep 30 ; command1

If you need to run two tasks at the beginning of a minute and at 30 seconds of the same minute, then you should add two tasks with the same interval, but specify one of them sleep 30 ; command1, where command1 a task to be performed. In this case, the execution of the second task will be delayed by 30 seconds.