4
votes

I have been trying to do random cron jobs where I choose the year month date and hour but the minute is randomised.

My first attempt was to run the cron every min and then compare a random date with todays date:

I inserted a random date into a database column fake_time in the format 2014-10-26 17 rand(0,59). In the php page where I run the cron every min:

if($row["fake_time"] == date("Y-m-d H i")){
    //do stuff
}

And this worked perfectly. But then I found out that I can't run the cron every min because my hostor (hostgator) wont allow me to! Have you got any ideas on how I can do this any other way?


Or should i just set it up on https://www.easycron.com/ instead?

2
This is good sample for you, check it: stackoverflow.com/questions/9049460/…Milad Abooali
What does your hoster allow you to do? I think the solution in @M.Abooali comment should work quite well.andy
Bigger question is - Why do you want do do this? WordPress for example, already has a plugin to check for site availability, for example.Leptonator
I am doing this as a blog post. Which posts to facebook and twitter. I dont want my followers to think I am a robot... I am.maxisme
How busy is your site? If you get consistent traffic you can just ditch cron alltogether, and use a database backed queue, that is serviced via user visits.Steve

2 Answers

1
votes

I think you are being limited by the number of cron jobs you can run in a day, IIRC hostgator has a daily limit for basic plan. To work around this limitation, IMO, you have two choices:

  1. Go to sleep for 60 seconds

    Basically, run the cron job at the required hour every day, and check for your condition, if it is not True, then go to sleep for 60 seconds.

    if($row["fake_time"] == date("Y-m-d H i")){
        //do stuff
    } else {
        sleep(60);
    }
    

    This way, you have a single cron job, though it runs for a long while. In case you can run the cron job only daily, and you want to run at random hour as well as minute, you can change your logic and go to sleep for 3600 seconds for hourly sleeps, and then go for minutely sleeps of 60 seconds.

    You might need to setup set_time_limit accordingly.

  2. Set up easycron

    In case your cron jobs are terminated abruptly because the time limit can't be set, you will need to hit using easycron service.

    In this case, put the above script code in a php file, say script.php, and schedule a cronjob to hit with a get request on this script. Your command in this case will look something like

    wget your.domain.com/script.php
    
0
votes

If there are no technical problems, you can do it with your php script (no install required).

if(rand(1, 5) == 1){
// do your staff
}

If you think that the script will not be executed often enough, you can reduce the difference rand(1,3)