cawecoy
cawecoy

Reputation: 2419

Manage cron jobs through PHP

I've been looking for a way to create, alter and delete cron jobs through PHP, but didn't find a way yet. I want to do it in an Amazon EC2 instance.

Is that possible? Any idea?

Upvotes: 1

Views: 2280

Answers (2)

cawecoy
cawecoy

Reputation: 2419

I found the following class on the Yang's Kavoir.com blog, and it's working perfectly.

class Crontab {

    static private function stringToArray($jobs = '') {
        $array = explode("\r\n", trim($jobs)); // trim() gets rid of the last \r\n
        foreach ($array as $key => $item) {
            if ($item == '') {
                unset($array[$key]);
            }
        }
        return $array;
    }

    static private function arrayToString($jobs = array()) {
        $string = implode("\r\n", $jobs);
        return $string;
    }

    static public function getJobs() {
        $output = shell_exec('crontab -l');
        return self::stringToArray($output);
    }

    static public function saveJobs($jobs = array()) {
        $output = shell_exec('echo "'.self::arrayToString($jobs).'" | crontab -');
        return $output; 
    }

    static public function doesJobExist($job = '') {
        $jobs = self::getJobs();
        if (in_array($job, $jobs)) {
            return true;
        } else {
            return false;
        }
    }

    static public function addJob($job = '') {
        if (self::doesJobExist($job)) {
            return false;
        } else {
            $jobs = self::getJobs();
            $jobs[] = $job;
            return self::saveJobs($jobs);
        }
    }

    static public function removeJob($job = '') {
        if (self::doesJobExist($job)) {
            $jobs = self::getJobs();
            unset($jobs[array_search($job, $jobs)]);
            return self::saveJobs($jobs);
        } else {
            return false;
        }
    }

}

Adding cron job:

Crontab::addJob('*/1 * * * * php /var/www/my_site/script.php');

Removing cron job:

Crontab::removeJob('*/1 * * * * php /var/www/my_site/script.php');

Upvotes: 3

Sammitch
Sammitch

Reputation: 32272

EC2 doesn't factor into the equation, and PHP has nothing to do with it other than creating files and calling a shell command. You need to look into the man pages from the crontab command.

The two commands that will be of use to you are:

  • crontab -l dumps the current crontab to stdout
  • crontab newcrontab.txt replaces the current crontab with what is contained in the file newcrontab.txt

Of course, these will only operate on the crontab of the current user. If you are root, or have sudo privileges you can specify the user with -u username.

Upvotes: 3

Related Questions