Cron provides a powerful way to automate scripts and commands in Linux to run on a recurring scheduled basis. A common use case is needing a job to reliably execute on the last day of each month, despite months having variable lengths. In this comprehensive guide, we will walk through how to leverage cron‘s capabilities to achieve this using the date command, dig into real-world examples, and share tips for debugging.

An Overview of Cron Jobs

Cron allows triggering tasks automatically at a specified interval using a special syntax. Here is a breakdown of the format:

* * * * * command to run
- - - - -
| | | | |  
| | | | |
| | | | ----- Day of week 
| | | ------- Month
| | --------- Day of month
| ----------- Hour
------------- Minute

We can control when a script or command runs by configuring values for the minute, hour, day of month, month and day of week. For our use case of an end-of-month job, we will want to focus on the day of month field.

Creating Cron Jobs

To create a cron job, we simply edit the crontab which lists tasks that will execute:

$ crontab -e

Then we can add our job such as a backup script to run daily at 1 AM :

* 1 * * * /path/to/daily-backup.sh

After writing the file, our cron job will run as specified.

Finding the Last Day of the Month

Since each month has a variable number of days in it, the question is how can we schedule a job where the day of month field won‘t reliably line up month over month?

The key is that we can leverage the date command to check if tomorrow‘s date is equal to the 1st day of the next month. Using this logic, if true, then today must be the last day of the current month!

Here is an example:

[ "$(date +\%d -d tomorrow)" = "01" ] && echo "Last day of month" 

This will output our message only on the final day of the month. By incorporating this date check, we can trigger cron jobs reliably on the last day.

Scheduling Cron Jobs for the Last Calendar Day

Putting together the cron syntax and date comparison, we can create cron jobs configured to run only on the last day of each month.

Here is an example:

0 1 28-31 * * [ "$(date +\%d -d tomorrow)" = "01" ] && /monthly/end-of-month.sh

Breaking this down:

  • 0 1 – Run at 1 AM
  • 28-31 – Day of month from 28 to 31, since any month could end on one of those days
  • date check – Verify tomorrow is 1st of next month
  • /monthly/end-of-month.sh – Script to execute if true

No matter whether the last day actually falls on the 28th, 29th, 30th or 31st, this cron will trigger on whichever day is the true final calendar day each month.

Next, let’s look at some real-world use cases.

Automating Database Backups on the Last Day

One of the most common use cases for an end-of-month cron job is fully backing up databases. This ensures you have a comprehensive backup containing all data for the month ready for archival.

For example, let’s setup a MySQL dump to run on the last day of the month at 1 AM and store in a Dropbox folder:

0 1 28-31 * * [ "$(date +\%d -d tomorrow)" = "01" ] && mysqldump -u root mydb | gzip > /dropbox/mysql_monthly/mydb_$(date +\%Y-\%m).sql.gz

This will create a date labeled SQL backup we could restore to snapshot that entire month’s data. For databases like MongoDB, the mongodump command provides similar backup capabilities.

Automating Report Generation and Processing

Another common use is running reporting jobs on closing days of accounting and billing periods.

For a software company generating monthly customer licensing reports, they may have a Python script that queries their database and outputs reports of active licenses. This could run on the last day of the month and email to the Finance team:

0 2 L * * [ "$(date +\%d -d tomorrow)" = "01" ] && /path/to/report-licenses.py | mail -s "EOM License Report" finance@company.com

This ensures the previous month is fully covered in the reports before closing it out.

E-Commerce Order Archiving

For e-commerce sites, each order placed can represent important business data that may be archived for accounting, tax, and analytics purposes. Rather than manual processing, the archiving tasks can be automated with a cron job on the last day of the month.

Here is an example Node script that collects all orders from the previous month then exports to a CSV file for long term retention:

0 3 28-31 * * [ "$(date +\%d -d tomorrow)" = "01" ] && node /server/archive-orders.js

Inside archive-orders.js, we can use a MySQL query to select previous month‘s orders by date, iterate over results to output CSV rows, handle file output, and confirmation emails. This allows new data to easily rollover on a monthly basis.

Debugging Cron Jobs

When creating cron jobs, things don‘t always go smoothly so having solid debugging skills and techniques is crucial. Here are some tips for troubleshooting cron jobs:

Check Log Files

Cron directs stdout and stderr to a log file which captures useful output and errors. To see history for the root user you can access logs at /var/log/cron. Specific paths may vary across Linux distributions.

Watch in Real-time

Use a tool like tail -f /var/log/cron to watch the logs in real-time as your cron job executes to pinpoint issues.

Verbose Output

Temporarily tweak your cron job to run every minute and output additional debug lines. Revert once stable.

Foreground Process

Launching the script in the foreground with cron syntax can help diagnose environment issues:

* * * * * /path/to/script.sh

Permissions

Double check scripts have proper execute permissions. Ownership should align with user running cron jobs.

With these tools and methods, you can attack cron issues from all angles.

Conclusion

While the varying number of days in each month poses a challenge to scheduling recurring tasks, by employing the handy Linux date command we can check for the last calendar day and trigger script execution reliably. Whether you need end-of-month database dumps, billing reports, e-commerce archiving, or any other process requiring completion of the full month, leveraging cron jobs is an efficient way to automate these critical business tasks. Careful testing and debugging is key to success as month turns over to month.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *