How to Set a Cron Job 24 Hours from Now


Improve your writing skills in 5 minutes a day with the Daily Writing Tips email newsletter.

On the latest project I am working, a mobile app, upon a certain action of the user on the server, I need to schedule a task to run exactly 24 hours later.

Cron to the rescue!

My first, naive idea, however, was to add a new cron job to the crontab whenever a user hit the server. This means I would need to calculate the exact cron configuration for each user/task, add it to the crontab, and then remove it when it was done.

As you probably know you define a cron job with 5 parameters: minutes, hours, day of the month, month and day of the week. Figuring out an offset of 24 hours in with those parameters is a nightmare. Not to mention changes of month and year.

I figured I was approaching the problem the wrong way.

Then a much better way came to me: simply store in the database the date and time of the user request, and have a script run every hour. That script should check the database to see if any user request was done 24 hours ago, and in positive case it would execute the task for that specific user.

Bottom line: never mess with creating a cron job for every new task or user request. Instead, always store those dates and times on your database, and create a cron job for a single script, with whatever frequency you need, and have that script check if it’s time to execute the scheduled task or not.

Leave a Reply

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