This guide presents how you can create a cron job, particularly one that executes on the last day of each month.
Working With Cron Jobs
You must create a crontab file for the given user to create a cron job in Linux, UNIX, or macOS. The crontab file contains tables with five fields where you can specify the date and time of the cron job and the full path to the script or command to run.
The syntax of a crontab file is as shown:
Use the command below to open the crontab file:
Here, we’ve opened a crontab file for the current user. If you need to schedule the job for a particular user, use the syntax below.
With your crontab file opened, you can add your cron job at the bottom.
For instance, if we need to create a cron job that executes every first day of each month, the cron job would be as shown:
The above creates a cron job that executes every 10:10 AM each month on the first day.
Schedule Cron Job on Last Day of Every Month
Determining the last day of the month can be challenging as some months have 28, 29, 30, or 31 as the last date. Besides, the field for the Day_of_Month takes a specific day and giving it a list of possible days would execute on an incorrect day.
The trick is to specify a command that checks if the next day is the first day of the month. If so, it means the current day is the last of that month and the cron job can then execute.
The command below checks and returns tomorrow’s date:
Using the same concept, we can create a condition that if tomorrow’s date returns as 01—meaning it is the first day—then the cron job to execute.
For instance, we can specify the command to echo a given output and verify that it will run when added to the crontab file. Let’s modify the command above as shown below:
Now, instead of the command displaying output to confirm that tomorrow is the first day of the month, we can set it to run our cron job.
The new command would be:
The cron job above would run every 1:30 PM of every last day of the month. Whether the last day is 28,29, 30, or 31, it will execute the specified script.
Note that we are listing the possible dates of every last day of the month and proceeding to give the command which checks that if the next day is the first day of the next month, then the current day is the last of the month. Once confirmed, it then executes the script.
Conclusion
This guide offered a hands-on guide on how to schedule one if you were stuck on scheduling a cron job that runs every last day of each month. We’ve seen how to determine the last day of any month and schedule a cron job.