So you want to trigger a cron job with PHP?
ComputersPublished April 29, 2010 at 1:02 am No CommentsAs a few of my friends know, I’ve been working on a special programming project lately. I developed most of it during Spring Break but had to take a break since my Distinguished Major Project took over my life until now. I still have some school work to do, but I couldn’t stop myself from tackling this problem today. One small part of my project involves creating a mailing list that will send emails to subscribers periodically (for example, let’s say every day). In order for that to happen, the mailing list script needs to run once every day. This is relatively easy to set up with a cron job, a time-based job scheduler in Unix systems.
The problem, however, is that I plan to distribute my project, complete with a custom content management system, to several clients. Needless to say, I don’t want them to have to figure out what the hell a cron job is, much less how to set one up. So I scoured the internet looking for a way to create a cron job with PHP. That should be simple, right? Maybe even use PHP to call a shell script which will in turn set up a cron job? After searching for a while I couldn’t find a satisfactory answer, and, well, I still don’t have one. But I do feel like I have a satisfactory alternative.
My script, which I call Pseudocron, has three components. (1) An administrator interface that includes text inputs for (a) the script to be executed periodically, and (b) the time delay (in seconds) between executions. This data is submitted to a MySQL table. (2) The actual pseudocron.php file, which checks to see if the time interval has been exceeded. If so, it runs the script and updates the time interval (now + interval) to prepare for the next execution of the script. (3) The script that is to be executed periodically. All three files are displayed below with thorough comments.
Yes – the nature of this script means that your web site will need visitors for it to run efficiently. If you want a script to execute every 5 minutes but you only get 1 hit per day, well, you’re out of luck.
Download (2kb)
1. create-pseudocron.php
/*
CREATE-PSEUDOCRON.PHP
v. 1.0
April 29 2010
By Benjamin Yobp [http://www.benjaminyobp.com/]
– Creates a pseudocron job
*/
include “pseudocron.php”;
?>
<html>
<head>
<title>Create a PseudoCron Job</title>
</head>
<body>
<form action=”create-pseudocron.php” method=”post” name=”add”>
<input type=”text” value=”.php file to execute” name=”file”>
<input type=”text” value=”Time in seconds between executions” name=”delay”>
<input type=”submit” value=”Submit”>
</form>
<?php
// Only run this if the form has been submitted
if($_SERVER['REQUEST_METHOD'] == “POST”) {
$file = $_POST['file'];
$delay = $_POST['delay'];
addPseudoCron($file, $delay);
print “<br><strong>Success!</strong>”;
}
?>
</body>
</html>
2. pseudocron.php
/*
PSEUDOCRON.PHP
v. 1.0
April 29 2010
By Benjamin Yobp [http://www.benjaminyobp.com/]
– Schedules a .php file to be run regularly at a given time interval
– Every time pseudocron.php is loaded in the browser it will check
to see if the specified time interval has passed.
Case 0: pseudocron.php waits patiently…
Case 1: the .php file you specified will be executed
– IMPORTANT: Create this MySQL table:
CREATE TABLE `YOUR DATABASE NAME HERE`.`pseudocron` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`script` VARCHAR( 20 ) NOT NULL ,
`interval` INT( 15 ) NOT NULL ,
`schedule` INT( 15 ) NOT NULL
) ENGINE = MYISAM ;
*/
// Connect to the SQL database
$dbhost = ‘localhost’;
$dbname = ‘DATABASE NAME’;
$dbuser = ‘DATABASE USERNAME’;
$dbpass = ‘DATABASE PASSWORD’;
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die(‘<font color=”#cd0000″><strong>Pseudocron error: could not connect to the database!</strong></font>’);
mysql_select_db($dbname);
// Call this function to create a pseudocron job
function addPseudoCron($script, $interval) {
$now = time();
$query = “INSERT INTO pseudocron VALUES (”,’$script’,'$interval’,'$now’)”;
mysql_query($query) or die(‘<font color=”#cd0000″><strong>Database error: could not create pseudocron job!</strong></font>’);
}
$query = “SELECT * FROM pseudocron”;
$result = mysql_query($query) or die(‘<font color=”#cd0000″><strong>Database error: could not select the pseudocron table!</strong></font>’);
while($row = mysql_fetch_array($result)) {
$now = time();
$thisRow = $row['id'];
$nextPseudoCron = $now + $row['interval']; // Sets the time for the next execution of the pseudocron job
$timeTillPseudoCron = $row['interval'] + $row['schedule']; // This variable is the time that pseudocron.php will check.
// It = the time interval + the time it was when the pseudocron job was last executed
if ($now >= $timeTillPseudoCron) { // “If the pseudocron job is due to be executed, then execute it!”
include $row['script']; // Run the desired .php script
$setSchedule = “UPDATE pseudocron SET schedule=$nextPseudoCron WHERE id=$thisRow “; // Update the schedule so that the pseudocron job can be executed next time!
mysql_query($setSchedule) or die(‘<font color=”#cd0000″><strong>Database error: could not update the pseudocron schedule!</strong></font>’);
}
else {
print “Sorry, not time yet!”;
}
}
?>
3. example.php
print “Hello world!”;
?>
There you go. I hope this was helpful! Sorry for the poor formatting in the above code boxes. If you download the .zip archive, the files will be tabbed and pretty looking.
