15 October 2014

The Power of CRON

An action on a website usually takes place by a user performing a task. An example would be a registration system sending a confirmation email. When a user enters their username and password then clicks submit, a script runs sending an email to that user informing them they must click a link to confirm their registration. This is a common workflow, however occasionally we need to perform tasks on a schedule. To do this in apache we use a CRON job.

A CRON job is a time-based task. You can set what time of day a task runs, how often it runs, and what exactly to run. Let’s assume our application is subscription based. People sign up and pay for a year. After that year is up, if they have not renewed their subscription we want their account to become deactivated. We cannot rely on the user remembering when to renew their subscription and we would probably want to inform them their subscription is expiring a month or so in advance. What we can do is create a script that runs every day checking for user subscriptions that are going to expire exactly a month, or 30 days, from the day the script runs.

That’s the concept. Now let’s put it into action.

Database

CREATE TABLE user_subscriptions (
uid INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(uid),
FirstName CHAR(15),
LastName CHAR(15),
Email CHAR(100),
expires DATE
)

cron.php

oct 3 image

 

 

 

 

 

CRON Command
00 20 * * * /home/user/scripts/cron.php

The above will run cron.php once a day at 8:00pm

 

 

Share This Article