PHP Classes

File: sample/samplejob.cli.php

Recommend this page to a friend!
  Classes of Martin Pircher   PHP Cron Job Manager Script   sample/samplejob.cli.php   Download  
File: sample/samplejob.cli.php
Role: Example script
Content type: text/plain
Description: Example script
Class: PHP Cron Job Manager Script
Add PHP scripts to be executed periodically
Author: By
Last change: Update of sample/samplejob.cli.php
Date: 9 months ago
Size: 2,031 bytes
 

Contents

Class file image Download
#! /usr/bin/php
<?php
/**
 * sample cronjob file
 * @version 2009-11-16 17:49:25 +0100
 * @copyright Martin Pircher <mplx+code@donotreply.at>
 * @author Martin Pircher <mplx+code@donotreply.at>
 * @link http://www.pircher.net/
 * @license http://opensource.org/licenses/MIT MIT License
 * @package Cronjob
 */

use \mplx\toolkit\cronjob\CronJob;

/**
 * Database configuration
 */
include 'config.inc.php';

/**
 * Check for CLI
 */
if (@php_sapi_name() != 'cli') {
    die(
'ERROR: This script will only work in the shell'.PHP_EOL);
}

/**
 * Include cronjob php class
 */
include dirname(__FILE__).'/../src/cronjob.php';

/**
 * Initialize
 *
 * create object and initialize database connection
 * database table has to be already created, this can be done by calling $job->createTable();
 */
$job = new CronJob('samplejob', $dbcfg);

/**
 * in case job is new then register it and schedule it for every 60minutes
 */
if (! $status = $job->getStatus()) {
   
$job->registerJob(__FILE__, 60);
   
$job->scheduleJob(time() + 60);
   
$job->enableJob();
   
$status = $job->getStatus();
}

/**
 * Locking
 *
 * in this sample we don't want to run the script multiple times so we lock it for the runtime
 */
if ($status['locked'] == 'y') {
    die(
'ERROR: Cronjob still running!?'.PHP_EOL);
}

if (
$job->setLock()) {
    echo
"Locked".PHP_EOL;
} else {
    echo
"Error on lock".PHP_EOL;
}

/**
 * here goes the jobcode...
 */
echo "EXECUTING SAMPLE CRONJOB...".PHP_EOL;
print_r($status);
echo
"SLEEPING 5s...".PHP_EOL;
sleep(5);

/**
 * Reschedule for next run
 */
$nextRun = time()+$status['interval'];
if (
$job->scheduleJob($nextRun)) {
    echo
"Rescheduled".PHP_EOL;
} else {
    echo
"Error on reschedule".PHP_EOL;
}
if (
$job->releaseLock()) {
    echo
"Unlocked".PHP_EOL;
} else {
    echo
"Error on unlock".PHP_EOL;
}

/**
 * Disable the job, will not run anymore
 */
if ($job->disableJob()) {
    echo
"Job disabled. To run by scheduler you'll need to enable the job.".PHP_EOL;
} else {
    echo
"Error on disable".PHP_EOL;
}