I have a database in MySQL which have entries of time. There are more than 1000 entries of time. I want to extract time and run a PHP script exactly at that time..
I have tried to run a PHP script continuously which check the time, but my server does not allow to run the script for more than 60 seconds.
EDIT. I have to check the database every second. Is there any alternative?
Use the pear package, System_Daemon
http://pear.php.net/package/System_Daemon/
Try Unix's cron.
You'll need some external service to execute the script. On a Unix box, that would be cron. On a Windows box, use Task Scheduler.
Have you thought about writing your process as a server daemon. It would start up and run in a while loop forever. Every few minutes or however often you'd like it could check the next x minutes of run times. You queue up your requests and whenever that time comes around you kick off the script you need to run. I don't think cron is what you'd want since you are trying to schedule future events at arbitrary times... And I'm sure it's what you are currently using to try and check the db every second.
Write a PHP script to read from the database and add entries to your crontab to make the script run at the desired time
Keeping a process running is not a very good solution, not least because you'll need to ensure it does keep running. Presumably you know when the next occurrence is going to happen - so use the 'atd' to schedule it - when triggered the script should also work when and how to schedule the next job.
This does mean that jobs are chained - and failure of one breaks the chain, also the granularity of most implementations of atd can be rather high.
You might want to look at using a more sophisticated scheduling tool like Nagios or a process monitoring type approach like DJB's daemontools or Oracle's OPMN.
C.
You must use the sleep(arg) function that pauses the PHP script for a given time and then continues.
sleep(50); //Pauses
myFunction(); //Runs after the pause
For example, this pauses the script for 50 seconds.
DJB's DAEMONTOOLS is great. So, apparently, is systemd and/or Upstart, though Remnant plays a true wanker.
The recommended Pear package - system_daemon looks great. However, the author now recommends to use new functionality that's readily available in Ubuntu: upstart
See his article on his own blog from 2012
Related
I have a site where auctions end a varying times. I need to send an automated email to the seller and the buyer after the auction is finished to notify them of the auction ending and the results. Obviously I can't really wait for someone to load the page to run the script so is there a good way to automate this by checking the current time and comparing that to the time of the auction end and running that script?
The site is on a UNIX server so a cron job is an option, but I'm concerned that running a cron job like that will put quite a load on the server.
A cron job runs at most once per minute.
Whatever load it generates on the server really depends on the kind of script you're going to run. Btw, I'm assuming that you're using cli to run the script (rather than just doing a curl http://mysite.com.
If your script takes longer than one minute (you should monitor this), simply either:
Increase the interval time between runs or,
Use a lock file to make sure no two instances of your script can run at the same time.
if (($fp = fopen('/tmp/mylockfile', "r+")) === false) {
die("Could not open lock file");
}
if (!flock($fp, LOCK_EX | LOCK_NB)) {
die("Could not obtain lock");
}
// run your code here
// release the lock and close file
fclose($fp);
OTOH If the script needs to run more than once per minute, you would need a different mechanism entirely.
Q: What is the best way to run a PHP script at a particular time, or interval?
A: Use cron
Q: Does a cronjob create a big load on the server?
A: Depends off course off your script. But checking if an auction should be closed, close it and send two emails shouldn't be to difficult. Be sure to create some kind of lockfile to make sure that if your script runs longer than the interval set, it isn't run twice.
Q: running a script with shorter intervals than 1 minute
A: Can't answer this one for you. Sorry :)
Use Cron. It allows you to run any command at most once per minute: http://clickmojo.com/code/cron-tutorial.html
As far as server load goes, it generally won't be a concern unless you are running a massive number of database calls very often on a very low-end server. I speak in generalities, but the idea is sound.
If you are using something else (besides PHP) to run your auction timer mechanism, I recommend you attach some code to that timer mechanism that also executes a mail-sending script when the timer runs down to zero and determines a winner.
Run the PHP script as a command line script. This will not put a load on the webserver - just a load on the server and you can easily run it via CRON.
If you add #!/usr/bin/php to the top of the script and change the execute bit on the file with chmod +x scriptname.php you can directly execute the script without passing it through php
http://php.net/manual/en/features.commandline.php
A couple of things you need to do this:
Store something in your auction information indicating whether you've sent this e-mail yet or not (could be a boolean or a date for when it was sent which might be null). Although I have to assume you need to do something besides send this e-mail? Like mark the auction as closed so no more bidding can take place?
A bit of code that finds auctions which need this e-mail sent: e.g. they've ended and have not yet been reminded.
Something to repeatedly execute the bit of code in 2. You could use cron. Alternatively you can write a pretty simple daemon for unix that runs constantly in a loop of (wait at least a few ms or more; do some stuff). The latter is a lot more work but in my opinion scales much better. See http://pear.php.net/package/System_Daemon for some useful tools if you're interested in this approach.
One thing to consider is how much you want to be careful about accidentally double-sending this e-mail. If you're only running this code in a single thread it's pretty easy but if you ever want to build out to the point where you have several different distributed machines that create and send these e-mails you have to be a bit more careful. If you're running it out of cron can you guarantee one run of it will always be finished before another one starts?
I have a line of code that needs to be executed from an user-defined start time to an user defined end time.
The problem is that a normal loop from start to end doesn't work because PHP gives me an error of "Execution Time Limit Exceeded".
How do I get this done without using CRON jobs? (I need to run my server on a Windows PC)
Windows or not it's not excuse. Any platform features tools to let you do scheduled tasks. So does Windows. Here is tutorial about setting up Scheduled Tasks on Windows to achieve same results like you can with cron.
EDIT
I need to do this on a web-browser. It needs to be platform independent.
You can't really. The only trick to do something close to cron w/o cron is to check dates on each request users made to your scripts and if the time is right, fire do some job. But if noone visit your site then you start nothing.
Other option is to setup cron which would do the request to your page (i.e. using wget, lynx, HEAD etc). But it still needs the "driving force" like cron or equivalent
Try to change your "Execution Time Limit" in your PHP.ini
I solved the problem. Using javascript and the setTimeout() function, I sent a GET request to the necessary php script and the line of code was executed after that delay.
As a possible alternative to using cron jobs, I found the sleep function. I have never used this before.
If I tell my script to run inside a kind of loop, and inside that loop I have an instruction like this
# sleeps for 86400 seconds or one day
sleep(86400);
will my script be launched again after 1 day? even if don't access it on my web browser again within that period?
I think is not possible, but I'm here to ask an expert about it.
The main problem with using PHP this way is, in my experience, not web server timeouts (there are ways to handle that with difficulty varying on the server and the platform) but memory leaks.
Straightforward PHP code tends to leak a lot of memory; most of the scripts I wrote were able to do hundreds of times as many work after I did some analysis and placed some unsets. And I was never able to prevent all the leaks this way. I'm also told there are memory leaks in the standard library, which, if true, makes it impossible to write daemons that would run for a long time in loops.
The script will timeout. You need to set it so that it won't timeout using set_time_limit.
I wouldn't do this I would either use a cron (that is a link) job if it is a regular task or an at (that is a link) job if the job is added at the run time of your script.
cron allows you to run a recurring job every day at 1pm for example whereas at allows you to schedule a job to run once for now +1day for example.
I have written a PHP 5.3 wrapper for the at queue if you choose to go down that route. It is available on GitHub https://github.com/treffynnon/PHP-at-Job-Queue-Wrapper
There is also time_sleep_until(). Maybe more useful to wake up on a specific time...
If you access the script through a web browser, it will be terminated after 30 seconds.
If you start the PHP script on the command line, this could work.
It would work, but your "startup time" will be subject to drift. Let's say your job takes 10 seconds to run, then sleeps 86400, runs another 10, sleeps 86400, etc.. You start it exactly at midnight on day 1. On Day 2 it'll run at 12:00:10am, on day 3 it's 12:00:20am, etc...
You can do some fancy math internally to figure out how long the run took, and subtract that from the next sleep call, but at the point, why not use cron? With cron the script will exit after each run, cleaning up memory and resources used. With your sleep method, you'll have to be VERY careful that you're not leaking resources somewhere, or things will eventually grind to a halt.
I had a similar problem before and found a php cron parsing class that will allow you to execute php similar to running crons. You can tie it to a commonly accessed script on your site if you don't have access to run crons directly.
I actually use this script as part of a larger cron job script:
a cron job runs every hour
an xml file for each sub-cron with a cron-like time component(i.e.- * */2 * * * php /home..)
the sub-cron script that will run if the current time meets the criteria of the sub-cron time component
a user interface is setup so that I don't have to manually add/remove sub-crons from the main cron
The cronParser class is here.
Many correct answers, but: Using sleep() means your script keeps running, and keeps using memory. Raising the default timeout of 30s will work, but again, this is bad idea. I suggest you use crontasks.
This is why legitimate cron jobs were invented. Just use crontab. Using a PHP script to do it will be EXTRAORDINARILY unreliable, buggy, and poorly timed.
Hope this is insightful.
I have a PHP script that needs to be run at certain times every weekday. Is cron or Windows task scheduler the only way to do this?
Is there a way to set this up from within another PHP script?
Depends how exact the timing needs to be. A technique I've seen used (dubbed "poor man's cron") is to have a frequently accessed script (a site's home page, for example) fire off a task on the first page load after a certain time (kept track of in the database).
If you need any sort of guaranteed accuracy, though, cron or a Windows scheduled task is really the best option. If your host doesn't support them, it's time to get a better one.
Apart from cron or Scheduled Tasks, you can have your PHP script to always run it. The process should sleep (within a loop) until the time has reached. Then, the process could execute the remaining functions/methods. Or, you can set up another script (which will act as a daemon) to check for the time and execute the other script.
Well since the web is a pull mechanism you have to have some sort of action that will trigger a PHP script to execute. cron is an option on *nix and task scheduler on windows. You could also write your own service that has a timer but only if needed, this is common on windows services for updaters, jobs etc.
One way you could do it is in the cron task just call a php script for each action needed. Or one php script that executes other tasks. The problem with web based tasks though such as PHP is timeouts. Make sure your tasks are under 60-90 seconds. If not you might look at using python , perl or ruby or even bash scripts to do the work rather than the PHP script.
cron seems like the best option for you though. You will have to call your script with wget. There are examples here: http://www.thesitewizard.com/general/set-cron-job.shtml
For instance this runs the script everyday at 11:
30 11 * * * /usr/bin/wget http://www.example.com/cron.php
Cron, of course, is by far the best way to schedule anything on *nix.
If this is in a remote server you do not have cron access to, you can setup cron/windows scheduler on your computer, to open a web browser to the page that contains the script you wish to run
You probably want to use cron (or windows scheduled tasks).
If you really wanted, you could set up another php script to run continuously with an infinite loop (with a sleep command inside the loop, say for 30 seconds or so) and then when you reach your desired day/time execute the other script via a shell command call. While possible, I can't think if a single good reason to use this method rather than cron/scheduled tasks
You can write a long running script that runs your main script in predefined times but it will be very unnecessary, error prone, and it will basically be a "cron rewrite in phph".
Using the real cron itself will be easier and a more robust solution. If you are packaging an application, you can put a file in /etc/cron.d which contains a single cron line running your application.
You'll need to use a cron job (under Linux/Unix) or a scheduled task under Windows. You could have another script running on a continuous basis which checks the time and executes a script at a specified interval, but using the OS-supplied mechanism is easier to manage and resilient to restarts, etc.
The Uniform Server project has some good suggestions on mimicking cron in environments where cron is unacceptable. Still though, if cron is at all an option, use it.
I have a php script that reads one file through http(the file is on other domain). I would like to read this file only once or twice a day, instead of connecting to it every time the website is refreshed.
Is there any other way than doing it with cron?
I dont want to use cron cause I prefer to setup this behaviour in the script itself .. so it is flexible, so I can use it anywhere without setting up cron every time.
thanks
I've done this kind of thing in the past when I didn't have access to cron:
$lastRunLog = '/path/to/lastrun.log';
if (file_exists($lastRunLog)) {
$lastRun = file_get_contents($lastRunLog);
if (time() - $lastRun >= 86400) {
//its been more than a day so run our external file
$cron = file_get_contents('http://example.com/external/file.php');
//update lastrun.log with current time
file_put_contents($lastRunLog, time());
}
}
If you can't or don't want to use use cron and it's ok to update it only when the page is accessed. You could cache the result of the HTTP request and only update it on a page load it if the cache is older than a day or whatever interval you choose.
You can also use Web Based Cron if you want to hit a site on a timed interval.
You could even use a database table - really simple in structure, id, date, script url, and whatever you need - and add a row every time you run the script.
Then, before run the script simply check the numbers of row for each day you have.
You can use a Cronjob. You can then run the php script by the command line.
php /someplace/somefile.php
The Cronjob would be the following if you update every day.
0 0 * 0 0 php /someplace/somefile.php
Since you explicitly state that you don't want to use cron, the only other way to do this (without something analogous to cron) is to set up your script as a daemon. However, unless you really need the flexibility that daemons provide, cron is much easier and simpler.
Here's one daemon walk-through.
If you're using a Linux distro with systemd:
I had a need for scheduling yearly based jobs, independent of the application (in case the system rebooted or anything like that), and I was given the suggestion to use systemd Timers. The Arch Wiki Page on it gives some examples.
If you are on a *nix environment you can use cron jobs
What's wrong with cron?
You have a couple choices with cron - your php can be invoked by the command line PHP interpreter, or you could use wget or fetch or the equivalent to invoke your PHP on the server.
In general, PHP run from within the context of the web server has a time limit on how long it can execute, so in general you can't set up "background" PHP threads to do stuff "later".