Issue
We know that an item in a cron table (or crontab) has the following format.
# ┌───────────── minute (0 - 59)
# │ ┌───────────── hour (0 - 23)
# │ │ ┌───────────── day of the month (1 - 31)
# │ │ │ ┌───────────── month (1 - 12)
# │ │ │ │ ┌───────────── day of the week (0 - 6) (Sunday to Saturday)
# * * * * * <command to execute>
Sometimes, I need to make a quick change by changing a value in some sub-expressions, say for example 8 instead of 7 in the "hour" sub-expression, in several lines.
Is there a way to store this value in a placeholder, so that I do not have to manually modify potentially many lines in the cron table?
Example
For example, I would like to store a value in a placeholder like this:
var wakeup=7
or like this:
const wakeup=7
or using some macro-like command, like this:
#define wakeup 7
so that I would write crontab lines like the ones below:
0 wakeup * * * wakeupscript.sh
...
...
*/5 0-wakeup * * * prewakeupchecks.sh
so that when I want those scripts to run at 8 and before 8 respectively, instead of at 7 and before 7, I would just need to redefine the wakeup
placeholder instead of manually changing all the lines.
Ideally, placeholders should store also intervals and frequency values, like 15-30
or */20
etc.
Solution
As far as I know, the simple answer is "no" for common cron implementations.
The crontab file format is very simple, and no variables or macros are expanded when interpreting it. In some implementations, environment variables can be set both to affect the behaviour of cron itself, and to be passed to the command when it's executed, but these don't affect the interpretation of the other lines of the file.
What you could do instead is build your own macro / templating system:
- Store the rules in a custom format
- Write a script that pre-processes them into the standard crontab format and output it to a temporary file
- Install that as the crontab using
crontab $tempfile
The pre-processor could even be something generic like M4, Perl, PHP, or even handlebars.js. All you have to do is remember not to edit the crontab by hand, so that it becomes out of sync with your template.
Answered By - IMSoP Answer Checked By - Clifford M. (WPSolving Volunteer)