Search code examples
phplinuxcronjobs

create cron job from another cron job


Good day to all. I need to do this:

  • create a cron job (no problem here)
  • the cron executes a php script
  • if some condition are met I need to create another cron using a date that is returned by the script

I have root access and everything. OS is centOS 5.5 (even thought I don't think it really matters as long as crons are supported)

To be more specific I need a cron that executes a php script that gets an exact moment of time from a database (hours, minutes, seconds) when to execute another script. The database can be updated at any moment. The first job is executed once every 10 minutes.


Solution

  • You can simply create a /etc/cron.d/generated crontab file in which your script will add generated entries.

    file_put_contents('/etc/cron.d/generated', ' ... entry contents ...', FILE_APPEND');
    

    As suggested by @The MYYN in his comment, at may be a good solution too, if you want to execute the script only once. In PHP you could invoke it like this:

    system(sprintf('echo %s|at %s',
        escapeshellarg($command),
        escapeshellarg(date('H:i d.m.y', $timestamp))
    );
    

    Or like this:

    $fd = popen(sprintf('at %s', escapeshellarg(date('H:i d.m.y', $timestamp))), 'w');
    fwrite($fd, $command);
    pclose($fd);