Wednesday, March 28, 2012

Automating db backup using php and cron

I have a script that backups up my DB. I need to call the script once a night and I have a cron script that is called every 15 minutes. I updated the cron script located at

moodle\admin\cron.php.

I added to the end of the script a simple conditional check to see if the time is between a specific 16 minute interval. If it is, which it should be once a night, then include the script file that contains the backup code. Like this:

Adding code to the cron.php file


$time = date('h:i');

if($time >= '03:00' && $time <= '03:16'){
include_once('dbBackup.php');
}

I excluded the if statement initially, to be sure I could include in the cron file. Once I saw the backup file called, I put the conditional back in place. I think the cron.php file has some special magic powers that might exclude the use of a include_once call, of course not, its a script file like any other.

Consequences of updating core moodle code


I kept the backup code in the external file dbBackup.php to minimize the amount of code inserted into a core moodle file, cron.php. When I update the moodle core, this cron.php file will get sacked and I will have to put the same code back into the file. This way its only 4 lines of code. The dbBackup.php file is about 40 lines of code.

I saved the dbBackup.php file into the admin directory (for now), where the cron.php script lives. I may move it into a safer place where the files wont get sacked by upgraded the moodle core.

1 comment:

  1. Hi,

    I am pretty new to moodle and I have been tweaking around the code here and there.

    I have a course which has several modules in it. I added a bit of code which prevents the user from accessing the second module in a course until it's been a week after the first module has been completed.

    Now, once a week has passed, I need to send an email to that user to inform that the second module can be started now. I can do the code for all this. What I need to know is to create a cron job for this part.

    I know what a cron does, what I need to know is exactly how to create a cron job which would run once everyday and which would call a script where I can do everything I need to.

    I am not sure how the MoodleCron.exe works, and I don't want a flood of emails either. Can you please help me with this?

    Thanks,
    Kevin

    ReplyDelete