Linux: create a cron expression based on current time plus the amount of time you want
Automate the creation of cronjobs!
Very often i need to create a cron job that will get executed in a few minutes from now, in case this is no recuring you can use a tool like the ‘at’ command which as a very nice syntax and is very easy to learn, but if its recuring you will need cron, the basic syntax of a cron expression isminute, hour, day of month, month, day of week or use '*' in these fields for any
Example: Every day at 8:00 am0 8 * * * <cmd>
Example: Every first day of week at 22:000 22 * * 1 <cmd>
Crontabs in a hurry
The basic expressions are easy to learn for simple examples but what if you need to create cron expressions on the fly? for example you are in a hurry and you need to create a cron that will run since the current day everyday in an hour plus the current time? we can use the date command that and produce output that is crontab compatible!
Example: Create a crontab expression that will trigger one hour since the current time for this day of the year.$ date '-d +1 hour' +'%M %k %d %m *';
05 23 07 05 *
This created a crontab expression that will trigger a command one hour later from our current time and will execute every 23:05 of May 7 every year!
The date format can be manipulated in such a way to match any crontab needs
Example: Create a crontab expression that will trigger one hour since the current time every day$ date '-d +1 hour' +'%M %k * * *';
09 23 * * *
This created a crontab expression that will trigger one hour later from our current time and will execute every day every month.
the date command can accept modification parameters in a human form
Example: add one day to current date
My current system date is May 07 the following will create a crontab expression with the current date time plus one day$ date '-d +1 day' +'%M %k %d %m *';
13 22 08 05 *
Example: create a cronjob expression that will execute at next Monday
Human friendly syntax of date allows to create dates like “next Monday”$ date '-d next monday' +'%M %k %d %m *';
00 0 09 05 *
You can find great examples in the man page of the date command
date(1) — Linux manual page (man7.org)
I hope you found this article interesting