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?
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:
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.
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
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)
Related
I have the following (simplified) batch email process set up under a Windows Server:
User performs action that requires an email be sent;
The data necessary to create the email is inserted into an SQL Server table;
Once every 6 hours, Task Scheduler calls a PHP file which goes through the table, creating and sending out each of the outstanding emails.
This works quite well, however the application owners would like certain sorts of email sent out more regularly, in this case, every 20 minutes.
My first thought was to set up another Task Scheduler entry, but that raises the issue of what happens every 6th hour, when both tasks will be run at the same time. It will also require creating another PHP file, which isn't really a problem, but is annoying.
The other alternative I considered was to set the scheduler to every 20 minutes, and incorporate the 'what do I send, and when' logic into the batch file itself - if it's 12AM, 6AM, 12PM or 6PM perform both sets of emails, otherwise just perform the 20 minute one. That does, however, require hardcoding those times, and doesn't seem like it should be the first resort.
Is there a better way to accomplish this?
After thinking about it a little bit more, I realised that I could accomplish what I wanted via the application of the PHP time() function and some modulo arithmetic:
$runTime = time(); //Set time the program was run, seconds since epoch
$modTimeHour = $runTime % 3600; //3600 seconds in an hour
$modTimeTwenty = $runTime % 1200; //1200 seconds in twenty minutes
//Task Scheduler doesn't always run exactly on the dot, so give it some leeway
if ($modTimeHour < 5 || $modTimeHour > 3595) {
//send emails - category 1
}
if ($modTimeTwenty < 5 || $modTimeTwenty > 1195) {
//send emails - category 2
}
By getting the seconds since epoch, and checking whether the modulo of the number of seconds in the time periods I'm interested in is within a certain range, I can have many different 'streams' all going out at their proper times.
I am writing a task which will be ran by as a Cron Job. I want the function to check if a file has been downloaded to the server yet. The time stamp check is fine, however what is the best way to make the check loop run every 15 minutes? Could I use sleep and then check the current time stamp againsed the time stamp I want the loop to terminate (5am)?
Cheers.
This is what cron does. Crontab allows you to set an interval to run a script. It is easy to specify 15 minute intervals. This way you won't have to worry about sleeping or error recovery or anything in your php script, just your logic.
http://www.electrictoolbox.com/run-cron-command-every-15-minutes/
I have a PHP-based site with bookings/appointments stored in a MySQL database.
I want to set an e-mail notification to be sent to each person who made a booking exactly 24 hours before their booking. Bookings are added through a regular PHP form.
I know I could add a script to, for instance, the index page that checks the database for any bookings that are in the final 24 hours, but that's unreliable since I won't be getting much traffic at first. So the index page could go hours without visits, and the notification would be hours late.
The other solution that came to mind is to set a cron job that runs every minute, calls a PHP script which checks whether any e-mails should be sent and sends them. But I'm not sure if this is overkill in a way; does anyone have a better solution than having something run in the background every minute?
To sum it up - is there a way to do this without cron?
Triggering the job from a web page is a very bad idea, for two reason: (1) if you don't get traffic to your site, the job doesn't run; (2) if you get a lot of notifications, the job will be slowing down the response to the web requests (assuming you invoke the job synchronously).
I would strongly discourage you from running a job every minute either - it definitely will be an overkill. Instead, think whether you really need "exactly 24 hours" as the interval or would "between 22 and 26 hours" be ok.
We have a similar requirements - and went about it by setting a job that runs every 4 hours and checks what notifications need to be sent for events starting between 22 and 26 hours form the time the script runs. This way, the script is only execute 6 times in a day and everything gets sent correctly.
If 4 hours approximation is not good enough, then think to the largest interval that's appropriate. I'm sure 1 hour should be sufficient. Have a script run once an hour (from cron) and check for events starting between 23 and 24 hours from the time of the run.
Remember that once your email is sent, it doesn't end up in the recipient's inbox immediately: sometimes it takes a few seconds, but sometimes it may take an hour or even more - so an extra hour difference in your script won't be a problem.
You don't need to use cron as an interval'd timer. You can set a very specific date and time when you want your job done.
Here's an article on the subject
For instance:
0 0 18 5 * <php command here>
Will run every May 18th at midnight. That's more than enough time to clear it before the next iteration (next year).
there is no way other than setting cron or sending request to server through periodic calls...below is post similar to your question, you may get idea.
Live redirect based on periodic server calls with JSON or AJAX
Thanks
a cron job every minute has no sense ! but you can do a cron job every hour because i think it doesn't meter a hour difference or 2 hours . without cron it isn't any other way . it will take about 2 second (at max) to complete so it is worth
i have script which must execute after every n minutes. n minutes is dynamic so that i could not set a cron job to call the script (at a specific time).
so what i did was i stored the time after every n minutes in an array so that when the script is executed, it will first check whether the current time is in the array. if it is found in the array, it continues to executes otherwise it exits.
to execute the script, i must use a cron job to run every minute to check the time in the array. unfortunately, my web host only allows 5 minutes as the least interval. so every time the script is called, i check whether the values between $current_time and $current_time + (4*60) // 4 minutes is found in the array. if it is, and if needed, i use time_sleep_until to delay the script until the time reaches the value found in the array.
so if my script executes at 10:05 and the value found in the array is 10:06, i let the script sleep until 10:06 before it continues to execute. however, if the sleep time is more than a minute or so, i get a Mysql server gone away.
how can i prevent this? or is there a better way to do this?
thanks!
A couple choices, which is better I do not know.
One, is make sure your script works with CLI and after that minute is up call it with the http://www.php.net/exec function (if your host allows it).
Two, is setup a script, with a possible hash as a key and use a header redirect after the minute is up, this would call the script brand new so a new MySQL connection is made.
A third option is to set the script up like in two, except setup a schedule task / cron job on your computer that opens that page (it would have to be in the webroot) and calls it every minute or however you want. This is not a set method, but depends on how much your computer is on.
Fourth, similar to the third but use a free cron job hosting service like: http://www.onlinecronjobs.com/en
Hope that helps. If I think of other options I will update.
Is there a simple way to have a php script execute some html at a certain times of the day?
For example i have on my home page a header and at certain times i want to be able to add something right under the header, in this case a iframe.
I know everyone mentioned cron jobs but how would this work with that? also is there an alternative? Its not available on all hosting
The idea of cron and scheudled jobs seems to run counter to what you're actually trying to do. If you want something to display (an iframe in this case) only during certain times, you can simply check the server time during each request, and opt to display it if you're within a given time period.
Something like this will produce the same effect as a cron job, with more granularity, checking the time at the exact moment the requst is made.
<!-- Your Header here -->
<?php
$hour = date('G'); // 0 .. 23
// Show our iframe between 9am and 5pm
if ($hour >= 9 && $hour <= 17) { ?>
<iframe .... ></iframe>
<?php } ?>
You can expand on the conditional statement to show the iframe multiple times per day, or have your script check whatever external condition you're looking to use to govern the display of your iframe.
Update:
Additional times or types of comparisons could be specified via something like
<?php
$hour = date('G');
$day = date('N'); // 1..7 for Monday to Sunday
if (($hour >= 5 && $hour <= 7) // 5am - 7am
|| ($hour >= 10 && $hour <= 12) // 10am - 12 noon
|| ($hour >= 15 && $hour <= 19) // 3pm - 7pm
|| ($day == 5) // Friday
) { ?>
<iframe...></iframe>
<?php } ?>
The idea of periodically adding/removing the iframe from below your header with a server-side cron/task scheduler job is far more complex than simply conditionally displaying it during each request.
Even if you have some specific task which must run, such as a periodically generated report, the actual job of displaying the results usually don't fall upon the periodic task. The PHP script responsible for showing that iframe would still query the database at the time the request is made for any new content to show, and display it if found, rather than the periodic task somehow modifying the script to include an iframe.
If you are running on Linux, then you could have a cron job.
If you are on Windows, then use Task Scheduler.
If you are in a hosted environment, you need to check to see if either is allowed.
cron on UNIX, launchd on OS X, and Task Scheduler on Windows platforms.
When you don't have access to cron jobs or scheduled tasks on your server, you can use online services such as http://pingability.com/ to hit your script at specified intervals. It is not perfect, but you can build in some kind of secret key and code that makes sure that the script doesn't get run multiple times within a certain time period. Might seem a little hacky, but I've used it on live systems to send out daily emails and it's been working fine for over a year now.
On Unix systems cron is your best bet.
Use a cron job or something similar, see f.i. cron jobs or PHP scheduler
You could add a PHP script to your crontab to automatically run the script at defined intervals. From the command line, enter crontab -e to add the entry to your crontab.
you can schedule the task as a cron job.