Run Function every Night

I am building a function-X which reports information about a selected Member.

Currently it will fire whenever a person visits his/her profile.

To make things even more useful, I would like to run function-X every day at some predetermined time (e.g. 12:00am) and then write it into a table. (This would allow me to not only have a “snapshot”, but also do “trending”.)

So, I need a way for PHP to run this function in the background automatically at the same time every day, versus requiring the Member to click on his here profile.

Is there a way to do this? :-/

Sincerely,

Debbie

You will need to do a cron job if on Linux or schedule a Task if on Windows. You can find tutorials on the web.

Yep running a Cron Job is the way to go.

Basically a “cron” tells the web server to run a script (your function-x) at a certain time of the day. So you could set it to run at 2am every day, or every hour at 15 minutes past the hour, or every Tuesday at 11.30am…

1.) How hard is it to learn to do cron jobs?

2.) Are you sure that would work, because what I really want is to just run one PHP function every night at Midnight. (I don’t necessarily need to run an entire script…)

3.) Why isn’t there a way to do this purely with PHP? (Programming in Unix sounds scary, PLUS I can’t do it on my local dev machine…)

Sincerely,

Debbie

You can run a file once a day triggered by the first time the page is loaded for that day. I’ve used a version of this on several projects where clients don’t have a clue how to setup a cron job for their site.

There are two parts,

crontab.php - the file that holds the last date the script was run.
fakecron.php - the page that controls everything. Note: files you wish to run are put in an array so you could have several run, sending emails etc.

I would suggest having both these files in your base directory as well as any files you wish to run.
The file fakecron.php should be included only on your primary index.php page.

include "fakecron.php";

crontab.php

<?php

// Set $lastrun = "never" to stop fakecon from running completely

$lastrun = "2014-08-02";

?>

fakecron.php

<?php
// Name of crontab file
$crontab = "crontab.php";
// List files to run
$jobs = array("myfile.php");
// Double check that file exists
if (file_exists($crontab)):
	include_once "$crontab";
	if (isset($lastrun)):
		if ($lastrun == "never") $error="true";
		if ($lastrun == date("Y-m-d"))  $error="true";
		if ($lastrun != date("Y-m-d") && $lastrun != "never" && !isset($error)):
		
			$ran = 0;
			foreach ($jobs as $job):
				if (file_exists($job)):
					include "$job";
					$ran++;
				endif;
			endforeach;
			
			// update crontab file
			if($ran != 0):
				$CTcontent = "<?php\
\\r\
\\r";
				$CTcontent .= '// Set $lastrun = "never" to stop fakecon from running completely'."\
\\r\
\\r";
				$CTcontent .='$lastrun = "'.date("Y-m-d")."\\";\
\\r\
\\r?>";
				if (is_writable($crontab)):
					$handle = fopen($crontab, "w");
					if (fwrite($handle, $CTcontent) === FALSE):
						// echo only while testing
						//echo  'Fake Cron error! Could not write to '.$crontab.".\
";
						//exit;
					endif;
					fclose($handle);
				endif;					
			endif;			
		endif;
	endif; 
endif;
?>

Note while testing you’ll need to keep editing crontab.php setting the date to yesterday but you’ll need to NOT have crontab.php open in an editor so it can be written to by the script. Learned that the hard way.

  1. Very easy. You’ll be writing one after 3 minutes of reading a tutorial.
  2. Absolutely will work – this is why cron jobs exist, to do exactly what you are wanting to do
  3. Something has to trigger the PHP script to execute.

In addition to the method above this post, you could use loops and the sleep() function to mimick a cron job. Not the best way to go about it, but technically speaking, very possible. At the very least, it would give you precise control of when and how often it runs, rather than waiting for a page load.
But either way, don’t do either of those methods, just run a regular cron. Much simpler, more reliable, and isn’t a constant drain on your server like my method is.

Definitely go with a cron. Using a php/sleep method isn’t efficient at all and you run into issues with server configuration… most notably max_execution_time in the php.ini which defaults to limiting scripts to a max of 30 seconds.

Cron is very simple. It’s not *nix programming at all. It’s a program/process that runs on the server and executes commands on a set schedule defined by you.

The most basic example would be something like the following.

Create a php file containing the commands/functions you want to be run (IE: cron.php):


function doSomething() {
    // code some stuff
}

doSomething();

Your hosting provider will most likely give you an area in your control panel to add cron jobs. To run every night at midnight, you’d add an entry like:


0 0 * * * php /path/to/your/cron.php

That will tell the server to execute cron.php using the PHP interpreter every night at midnight.

Of course your setup will vary, and as such the process will vary, but in most cases it will be very similar to the above. Still though, read through the tutorials.

Okay, thanks for the tips and encouragement Keith (and arout77)!

When I get a new VPS for my new website in a month or so, then I’ll see what my hosting provider offers and go from there.

Thanks!

Debbie