skip to Main Content

I want to create cron jobs from within PHP, a bit like in cPanel or Plesk but I’m stuck. I want to do this programatically and not force the user to go to cPanel to create the crons manually…..

Tried many things, read many things… including here on stackoverflow, nothing works.
I try editing crontab from php like shell_exec(‘crontab /pathtomycronfile/cron.txt’) and then editing the cron file itself but it doesn’t work. User is ‘apache’ and I tried setting the crontab for apache .. doesnt’t work either …

Please can anyone help with this? Have you been able to create cron jobs from php before?

2

Answers


  1. Cron jobs normally needs to be created from Controlpanel from the host provider.
    I dont think there is a way to do from program.

    Login or Signup to reply.
  2. Under some *nix systems, crontab will store each user-specific cron file in e.g. /var/spool/cron/crontabs/[USERNAME] . They’re not intended to be edited directly, but you could get PHP to do so.

    You might also need to change the permissions on the containing directory, so that PHP can see the file to edit it. You could then do so with e.g:

    <?php
    $user = get_current_user();
    $cron_file = fopen("/var/spool/crontabs/$user", "a");
    fwrite($cron_file, "n* * * * * touch /tmp/testcronn");
    fclose($cron_file);
    

    To be honest, though, this is very dangerous. Instead, you should consider having a cron.php, which gets called every 15 minutes, and put all your logic about what actual tasks should be carried out at a given quarter-hour in that cron.php. Don’t edit the crontab to put the logic in there.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search