I currently have a system where on the client side this Update function is called every X amount of seconds:
var Update = function(){
$.getJSON("PHP/Update.php",{
userid: userID },
function(json){
doSomething();
});
}
In the PHP file some values are updated and these new values are sent back to the client.
<?php
session_start();
include 'dbconnect.php';
$userid = $_GET['userid'];
//Change some values in the database
//Add these new values to $json array
echo json_encode($json);
mysqli_close($link);
?>'
This works great when there is exactly one client active at all time. Not so much when there are multiple or no clients active. So what I want is that this PHP files gets called once every X amount of time, regardless of how many clients there are. I realize I probably have to create a loop in PHP but I just can't get it working. Can anyone tell me how I'm supposed to do this? Thanks in advance.
The tool you use to schedule things in unix-style operating systems is cron. If your server runs MS Windows, you'll need to use some other scheduler.
There are a couple of ways that you can use cron to run your script.
First off, if you have a CLI version of PHP available (as opposed to an Apache module or a fcgi version), you can run it directly. On my system, a cron job to run the script once per minute might look like this:
* * * * * /usr/local/bin/php /path/to/your/script.php
Note that on your system, the php binary might be located in /usr/bin/ or /opt/local/bin/ or somewhere else. You'll need to check with your operating system's package repository to find out where, or type which php from a terminal.
If you use a "shebang" at the beginning of your script, you can get away with a simpler cron job:
* * * * * /path/to/your/script.php
More information about running PHP shell scripts can be found here. A word of warning though... If you launch scripts directly like this, they will run as the user who owns the cron job, which may have security (or at least permission) implications. If you don't understand what this means, please ask more questions before doing it!
If you don't have a command line PHP available, you can still have the PHP script run via cron, by fetching it from a command-line HTTP client like curl or wget or fetch (depending on your operating system). For example:
* * * * * curl -o /dev/null http://example.com/path/to/script.php
or
* * * * * wget -O /dev/null http://example.com/path/to/script.php
On a unix system you can man crontab for instructions on how to install cron jobs, and probably man 5 crontab (depending on your operating system) for instructions on the format for setting specific times. Note that cron uses 1-minute granularity. If you want greater frequency than that, you can fake it. For example, for three times per minute:
* * * * * /path/to/your/script.php
* * * * * sleep 20; /path/to/your/script.php
* * * * * sleep 40; /path/to/your/script.php
And if you want lesser frequency, you use crontab's documented format. For example, every five minutes on weekdays but every 10 minutes on weekends:
*/5 * * * 1-5 /path/to/your/script.php
*/10 * * * 6-7 /path/to/your/script.php
Related
I'm Working on a php app where I need to have a number count in a sql data base reset at the first of the month and at 12am everyday via PHP and MYSQL.
I have googled but found nothing. As far as I know PHP needs to be accessed by a client to be manipulated.
What is the best method of having the server do this on its own?
You can use crontab
* 0 * * * /path/to/my/script
You can use cronjobs. On windows 'scheduled tasks', on linux crontab. For linux:
crontab -e
A line have to look like this to be called every day 0 am:
* 0 * * * /bin/php -q /script/path
Or, to call the file via web but do not get the content:
* 0 * * * wget --spider "http://url.com/cron.php"
If you do not have a dedicated server, check your webspace control panel for this or ask your webhoster.
I wrote a PHP script that push a CSV file into a database. I want to do this automatically every minute. I know there is a way via cron on Linux but I don't know anything about bash and think cron can't give my PHP file a callback, so I can show a progress bar for the user to see the timer interval. What do I do?
You can enter your jobs using crontab -e. If your default editor is vi, I recommend to change it nano using export EDITOR=nano because it is easy to use for starters.
Every line of the crontab file represents a job. The first 5 tokens are : minute, hour, day of month, month, day of week respectively, the last one is command so in your case first 5 tokens will be * * * * * that means run this job every minutes when the second is '00'.
You can call your php files directly using this command : php /var/www/cron.php & or using a browser wget -O /dev/null http://example.com/cron.php If you use first one you cannot use some $_SERVER variables but if you use second one, it is like a real browser.
In your case you can use like this :
* * * * * wget -O /dev/null http://example.com/cron.php
to add a cron and make it run every minute, type crontab -e and add the following line
* * * * * command you need executing
example:
* * * * * ls -l /home/ > /usr/local/users.txt
* * * * * df -h > /tmp/filesystem_usage.txt
* * * * * service httpd restart
Look at this for a starter: http://kvz.io/blog/2007/07/29/schedule-tasks-on-linux-using-crontab/
Also remember that cronjobs don't support all $_SERVER vars like 'DOCUMENT_ROOT' and 'HTTP_HOST', so try to avoid them, or use a workaround.
Some 'callback' possibilities:
- Let your script trigger another script
- Redirect the output of your cron to an another bash script
- ...
I have 50 Wordpress installations running on 1 server. Every Wordpress website has a script which must execute every 5 minutes. I don't want to use the build-in cron of Wordpress and want to run the scripts from cron. What is the best solution?
*Solution 1: create a cron job for every individual wordpress installation *
5 * * * * /usr/bin/php /wordpress-site-1/cron.php
5 * * * * /usr/bin/php /wordpress-site-2/cron.php
5 * * * * /usr/bin/php /wordpress-site-3/cron.php
... + 47 other scripts
*Solution 2: create 1 cron job and run a bash script *
5 * * * * /run/the-script
The script:
#!/bin/bash
# include the 50 sites in array
array=( wordpress-site-1 wordpress-site-2 wordpress-site-3 ...)
for i in "${array[#]}"
do
{execute php file)
done
By far, having 50 singular crons is much more efficient than have it run in one script. The only downside is that you'll have to insert 50 lines in your crontab. But hey, if that's everything...
Reasons for having 50 crons instead of one:
If one of the crons fails, the others will still run
If one of the crons fails, you'll be notified and don't have to do complex log-analysis to find out which one of your crons failed
You don't have to worry (or worry less) about script timeouts, memory usage, etc: 50 scripts executed in one time is about 50 times heavier then having them executed one by one
You can divide payload on the server
(You can probably think of some more)
As for the last point (dividing payload), I'd suggest to execute the first 10 scripts at zero, 5-past, 10-past etc, and the next 10 scripts a minute later. This way they don't run all at once, causing a high peak-load every 5 minutes:
0,5,10,15,20,25,30,35,40,45,50,55 * * * * /usr/bin/php /wordpress-site-1/cron.php
... cron 2 - 10
1,6,11,16,21,26,31,36,41,46,51,56 /usr/bin/php /wordpress-site-11/cron.php
... cron 11-20
... etc.
This is a pattern that you could use:
0,5,10,15,20,25,30,35,40,45,50,55 * * * *
try this solution:
cat cronjob
0,5,10,15,20,25,30,35,40,45,50,55 * * * * /usr/bin/php /wordpress-site-1/cron.php
.
.
.
0,5,10,15,20,25,30,35,40,45,50,55 * * * * /usr/bin/php /wordpress-site-50/cron.php
Then:
chmod +x cronjob
chmod +x /wordpress-site-1/cron.php
.
.
.
chmod +x /wordpress-site-50/cron.php
/etc/init.d/crond start #redhat based servers like centos
/etc/init.d/cron start #debian based servers like ubuntu
crontab cronjob
NOTE: You can use for loop to make it easier.
if you want every script run per 5 min, you can do this:
*/5 * * * * /run/the-script
I currently have a PHP website built with codeigniter, and i'm having issues with CLI and cron jobs.
The CLI is setup so the controller running the script is found in the /application/controllers/scrape on the server (looking via the ftp) this would be /public_html/application/controllers/scrape, the function to run is called all_sites.
I'm hosted with TSOhost and can successfully run the command using the browser via URL (website.com/index.php/scrape/all_sites)however the script times out, hence the need to use a cron job to run the script.
So far i have tried the following raw cron commands in the advanced mode in the TSOhost control panel when trying to get the script to run daily:
The TSOhost technician set this up
03 19 * * * /usr/bin/php-5.3 /var/sites/s/website.com/public_html/application/controllers/scrape.php (didn't work)
0 6 * * * /usr/bin/wget -O /dev/null -o /dev/null http://www.speeddatemate.com/index.php/scrape/all_sites
0 6 * * * /usr/bin/php-5.3 /var/sites/s/speeddatemate.com/public_html/application/controllers/scrape/all_sites
03 19 * * * /usr/bin/php-5.3 /var/sites/s/speeddatemate.com/public_html/application/controllers/scrape.php
03 19 * * * /usr/bin/php-5.3 /var/sites/s/speeddatemate.com/public_html/application/controllers/scrape/all_sites
10 18 * * * /usr/bin/php-5.3 /var/sites/s/speeddatemate.com/public_html/index.php scrape all_sites
TSO host have stated:
For referencing your site path, use /var/sites/s/website.com
The path to PHP 5.2 is /usr/bin/php and for 5.3 it's /usr/bin/php-5.3
The technician also said:
"To run from CLI you would need to find a way to get those parameters into the script, they can't be appended to the command."
Although is this not the Point of the command?
I've also tried running it via the "make a http request" option which creates the raw job as:
0 6 * * * /usr/bin/wget -O /dev/null -o /dev/null http://www.speeddatemate.com/index.php/scrape/all_sites
Again this does not work.
I've searched high and low to find a way to get this working and read various posts and tried various methods nothing has worked. Can anyone help?
First off, don't bother setting up a cron job unless you have it working on the command line. You will end up mixing different things and generating a plethora of unwanted possibilities for debugging which will confuse you further.
Now, you are saying that
I can successfully run the command using the browser via URL (website.com/index.php/scrape/all_sites), however the script times out
This could be because the script takes longer than 30 seconds to complete, and thus is hitting the max-execution-time in php. Check this.
If this is the case, check this and answers over here and here to resolve it by increasing the limit.
Once you have a working version of the script, either via browser or via command line, you can go ahead and schedule the cron jobs, like already shared by your TSOhost tech support.
03 19 * * * /usr/bin/php-5.3 /var/sites/s/website.com/public_html/application/controllers/scrape.php (didn't work)
0 6 * * * /usr/bin/wget -O /dev/null -o /dev/null http://www.speeddatemate.com/index.php/scrape/all_sites
Once again, setup the crons only after you have the other pieces working.
If it still doesn't work, give more info regarding:
What exactly the script does? Does it download something, does it backup something; update the question with whatever it does.
What parameters does it require? and how were you passing them via the url?
What do the logs say? Assuming your webserver is apache, you can usually find them at /var/log/apache2/error.log and /var/log/apache2/access.log.
EDIT 1
OP says in comments that php index.php scrape all_sites works for him.
Assuming that works from the root of of his app, where path to index.php can be asssumed to be /var/sites/s/website.com/public_html/application/index.php, try this cron job then
03 19 * * * cd /var/sites/s/website.com/public_html/application/ && /usr/bin/php-5.3 index.php scrape all_sites
If possible, schedule it for a time closer to current time rather than a fixed job for 19:03
If this still doesn't work, and assuming the max-execution-time has already been taken care of, the problem could be with one of your environment variables - your cli shell environment is having some variables that are missing from your cron environment.
In my experience, I have found that PATH variable causes the most troubles, so run echo $PATH on your shell, and if the path value you get is /some/path:/some/other/path:/more/path/values, run your cron job like
03 19 * * * export PATH="/some/path:/some/other/path:/more/path/values" && cd /var/sites/s/website.com/public_html/application/ && /usr/bin/php-5.3 index.php scrape all_sites
If this doesn't work out, check all the environment variables next.
Use printenv > ~/shell_environment.txt from a normal shell to get all the environment variables set in the shell. Then use the following cron entry * * * * * printenv > ~/cron_environment.txt to get the variables from the cron environment.
Compare the two - shell_environment.txt and cron_environment.txt for any unset variable which you need to tinker with in cron environment.
First of all make sure your script run as expected from your browser. If so then you can try to run it from command line. Lets assume following is your controller.
<?php
class Scrape extends CI_Controller {
public function all_sites($some_parameter = 'working')
{
echo "Its {$some_parameter}!".PHP_EOL;
}
}
?>
As per your provided information to run the command you can run
/usr/bin/php-5.3 /var/sites/s/website.com/public_html/index.php scrape all_sites
And set cron as
03 19 * * * /usr/bin/php-5.3 /var/sites/s/website.com/public_html/index.php scrape all_sites
If you need to pass a parameter, pass the parameter like:
/usr/bin/php-5.3 /var/sites/s/website.com/public_html/index.php scrape all_sites "Working fine"
Enjoy!
You can read reference document about Running via the CLI from codeigniter here
I have a database with a bunch of links that I want to keep updated. Basically if a link returns a 404 error code I want to remove it from the database. I have a script that I am using however I need to run it manually. How can I make this work using CRON?
in your shell as cron user (or root):
crontab -e
This will bring up your crontab file in your editor. Add a new line something like this:
* */12 * * * /path/to/script
Save/exit the file.
Now for a quick lesson on cronjobs:
-The first 5 arguments in the line tell how often, or when the cron daemon will execute the 6th argument.
-From left-right, arguments represent: minutes, hours, days, weeks, months
-An asterix (*) tells the cron to run on all values of it's associated time measurement (example * * * * * means to run every minute, of every hour, of every week, and of every month!)
In my example, * */12 * * * means to run every 12 hours.
Check out: http://kevin.vanzonneveld.net/techblog/article/schedule_tasks_on_linux_using_crontab/
To run a PHP script with cron you can use the PHP executable and the path to the script.
On most linux systems you want to edit your cron file (the crontab) with the command crontab -e. This will open up a command line based editor and you can just append your new job to the bottom of the file using this format.
<minute> <hour> <day_of_month> <month> <day_of_week> php /path/to/script
If the commands dont work for you let me know what distribution you are using and I can modify the instructions.
/usr/bin/php -q /home/user/public_html/script.php