My task is to specify time in CRON considering YEAR field. How can I do it?
4 Answers
As indicated in earlier posts, you cannot indicate a year field, it is, however, possible to mimic it:
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7)
# | | | | |
# * * * * * command to be executed
0 0 1 1 * [[ $(date "+\%Y") == 2020 ]] && command1
0 0 1 1 * (( $(date "+\%Y") % 3 == 0 )) && command2
0 0 1 1 * (( $(date "+\%Y") % 3 == 1 )) && command3
Here, command1 will run on the 2020-01-01T00:00:00, command2 will run every 3 years on the first of January at midnight, it will run so on 2019, 2022, 2025, ... . command3 does the same as command2 but has one year offset, i.e. 2020, 2023, 2026, ...
note: don't forget that you have to escape the <percent>-character (%) in your crontab file:
The "sixth" field (the rest of the line) specifies the command to be run. The entire command portion of the line, up to a newline or a "
%" character, will be executed by/bin/shor by the shell specified in theSHELLvariable of the cronfile. A "%" character in the command, unless escaped with a backslash (\), will be changed into newline characters, and all data after the first%will be sent to the command as standard input.source:
man 5 crontab
2 Comments
crontab -e; while it worked good directly in bash): [[ $(date "+\%Y").% in cron.Crontab (5) file format has no YEAR field. You could try running a cron job @yearly (at 00:00 on New Year's day) which looks at the current year using date(1) and updates the current crontab file to one appropriate for the new year.
1 Comment
Standard cron doesn't support a year field, but it's worth noting that some implementations support an extended crontab format with a sixth year field, such as nnCron. Not every cron is created equal.
Comments
var task = cron.schedule('0 0 1 1 *', () => {
console.log('Printing this line 1ST JANUARY OF EVERY YEAR in the terminal');
});
It is work for considering YEAR field.. @mart7ini
atinstead of a crontab.atwill execute your task a single time, similar as cron does.