Say I want a php script the run the function itstime() every hour. Other than setting up a cron job on the server how can I do this?
Or is this not possible because php scripts need to be opened to be ran?
Thanks.
EDIT: I want to write some information to a log file and depending on some variables send it in an email.
Well, I definitely recommend the cron job for the purpose. But theoretically, you could have a PHP script run itstime(), sleep for an hour, and loop. This is pretty crazy, though.
The script would look like:
<?php
include('whatever.php');
while(true) {
itstime();
sleep(3600);
}
?>
One would probably run it with nohup php mycrazyscript.php & to detach it from your terminal and make it keep running, and using pkill -f mycrazyscript to terminate it.
The reason this is crazy is that now you've got a sleeping PHP process hanging around doing nothing for 59 minutes out of every hour, and you have to make sure it's both running and running at the right time, both of which cron would take care of for you.
Only appending to chaos' answer, so give him credit.
mrlanrat - see this
If you don't have access to cron, but do have access to a moderately busy webserver, you can use it to trigger your function every hour. This is how WordPress gets around needing cron. Here's how you might do it:
<?php
$lastrun = get_last_run_time(); // get value from database or filesystem
if( time()-$lastrun > 60*60 ) {
itstime();
set_last_run_time(time()); // write value back to database or filesystem
}
// The rest of your page
?>
Of course, there's a pretty serious race condition in this code as is. Solving that is left as an exercise to the reader.
https://www.setcronjob.com/ and various other sites, provide a web based solution for this. You can set it up to call a php script with your code in it every hour or whatever you want
<?php
itstime();
?>
Related
I am trying to allow my simple website to check the time, so that if the set alarm time is equal to the real time the alarm goes off.
I'm using PHP (and I am pretty sure it must be in PHP due to using LEDs and python). I know this is relatively easy thing to do in js for example.
I have the variables:
$setTime = "$hour$hour2:$minutes$minutes2";
$realTime = date("H:i");
and a if statement:
if ($realTime == $setTime) {
exec("sudo python /home/pi/lighton_1.py");
}
else{
exec("sudo python /home/pi/lightoff_1.py");
}
This all works if when I load my website the real time = the set time however if not it won't. I somehow really want to check the if statement so often somehow. I have tried loops, functions etc and haven't had much success however my coding is a bit basic at the moment. Wondering if anyone knows this solution, (could be very simple?) Need help fast please. Thank you!
You need to understand how your PHP code is triggered. When used to host a website, it is triggered, when someone requests a page. Now, what are the chances than someone will request this page when "$realTime == $setTime". Unless you host a very busy site, the chances are very small. You could have a web page run a JavaScript to continuously refresh the page. Even in this case you may want to say "$realTime > $setTime".
You could alternatively run your PHP from a scheduler like a Unix Cron job, or some kind of PHP scheduler, but then you have to say "$realTime > $setTime", because scheduler may also not run this statement at the exact moment.
I'm pretty new to PHP. This is my first time actually, so I apologize in advance if the question sounds dumb.
I have a php script which fetches data from an external API and updates my database regularly. I know that the best way to do this is to use a cron job. However, I am using an infinite loop which sleeps for a particular time between each update.
Now, I need to allow the user (admin) to start / stop the script and also allow them to change the time interval between each update. The admin does this through a UI. What is the best way to do this? How do I execute the script in the background when the user clicks start and how do I stop the script?
Thanks.
I think the ideal solution would be the following:
Have the background job run as a cronjob every minute (instead of a loop which can cause memory leaks). PHP was not designed to be a daemon.
Set a DB flag in the cronjob for on/off, everytime it runs it checks if its on or off, if off it exists if on it continue.
In the UI you turn that flag on or off depending on what the admin needs.
I think that is the best way to go (and easiest).
You might want to take a look at Threading in PHP -> http://www.php.net/manual/en/class.thread.php
An other option is to either set a SESSION (which is a little tricky, since you won't catch it in the same call) or you generate a file wich tells the script to stop/exit/fail/what ever if that file exists.
How can I make a scheduler in PHP without writing a cron script? Is there any standard solution?
Feature [For example]: sent remainder to all subscriber 24hrs b4 the subscription expires.
The standard solution is to use cron on Unix-like operating systems and Scheduled Tasks on Windows.
If you don't want to use cron, I suppose you could try to rig something up using at. But it is difficult to imagine a situation where cron is a problem but at is A-OK.
The solution I see is a loop (for or while) and a sleep(3600*24);
Execute it through a sending ajax call every set interval of yours through javascript
Please read my final opinion at the bottom before rushing to implement.
Cron really is the best way to schedule things. It's simple, effective and widely available.
Having said that, if cron is not available or you absolutely don't want to use it, two general approaches for a non-cron, Apache/PHP pseudo cron running on a traditional web server, is as follows.
Check using a loadable resource
Embed an image/script/stylesheet/other somewhere on each web page. Images are probably the best supported by browsers (if javascript is turned off there's no guarantee that the browser will even load .js source files). This page will send headers and empty data back to the browser (a 1x1 clear .gif is fine - look at fpassthru)
from the php manual notes
<?php
header("Content-Length: 0");
header("Connection: close");
flush();
// browser should be disconnected at this point
// and you can do your "cron" work here
?>
Check on each page load
For each task you want to automate, you would create some sort of callable API - static OOP, function calls - whatever. On each request you check to see if there is any work to do for a given task. This is similar to the above except you don't use a separate URL for the script. This could mean that the page takes a long time to load while the work is being performed.
This would involve a select query to your database on either a task table that records the last time a task has run, or simply directly on the data in question, in your example, perhaps on a subscription table.
Final opinion
You really shouldn't reinvent the wheel on this if possible. Cron is very easy to set up.
However, even if you decide that, in your opinion, cron is not easy to set up, consider this: for each and every page load on your site, you will be incurring the overhead of checking to see what needs to be done. True cron, on the other hand, will execute command line PHP on the schedule you set up (hourly, etc) which means your server is running the task checking code much less frequently.
Biggest potential problem without true cron
You run the risk of not having enough traffic to your site to actually get updates happening frequently enough.
Create a table of cronjob. In which keep the dates of cron job. Keep a condition, if today date is equal to the date in the creonjob table. then call for a method to execute. This works fine like CRON job.
Is it possible to run a php script after every 100ms ? This script will check a database for changes and then the changes will be reflected into some other database. I am already doing it using Triggers. But I want to know if there is any other way to do it without using Cron and Triggers. I will be using Linux for this purpose.
Thanks
Running something every 100ms almost means that it runs all the time , might as well create a daemon that continuously loops and executes
or use triggers. Essentially on every database change it will copy to another table/db.
http://codespatter.com/2008/05/06/how-to-use-triggers-to-track-changes-in-mysql/
It is not possible to do this with cron (it has a max frequency of one minute) and this is a really bad idea. You will be running a whole new php interpreter ten times per second, not to mention doing database connection too.
Far better perhaps would be to run one program that re-uses it's connection and checks every second or so.
Sounds a little like you are trying to make your own database replication or sync between two databases.
You could write a daemon to do it, essentially a script which continually runs in memory somewhere to then run whatever code you want to.
So that daemon would then do the database processing for you, and you wouldn't have to call a script over and over again.
Use your favorite programming language and set up a permanent loop to run it every 100ms, then put the script into inittab with 'respawn' (man inittab for complete syntax). Finally, init q to reload init.
It's best if you write a little daemon for that. Use the pcntl functions to do so. In your case you might get away with:
<?php
while (1) {
usleep(100000);
if (pcntl_fork() == 0) {
include("/lib/100ms-script.php");
exit;
}
// else pcntl_wait(); eventually
}
I'm assuming that this is in reference to some type of web page to be created. If so, this sounds like this is a job for Ajax, not PHP. As you may already know PHP processing is done on the server side. Once processing is complete the page is served up to the client.
With Ajax/JavaScript processing can continue via the browser. You can setup a timer that can then be used to communicate with the server. Depending on the output of the response the page may be updated to reflect the necessary changes.
I have a hosted websolution and a script that update information backend for the site.
My webhost allows cron and I have made a script that wget's to every hour.
The script checks the db-table with posts to update for the oldest updated post and update that. In the end of the script I use javascript refresh to do the same procedure again this time with the second oldest updated post and so on until all posts are run through. If I open the script in my browser it works fine but when my host sets up the cron the script does not continue after the javascrpt refresh.
How can I solve this with another refresh solution that will work until the my statement stops it just by letting cron start the script?
(I changed to this solution from one where all posts were updated in one pageload but since it started to time out I went with this)
script.php
$limit=3600;
//Select the oldest updated post
if($last_update<$update_to_limit){ //check if the post was updated during this run
// Script that update the post and below the java refresh that repeats the script.
?>
<script type="text/javascript">
<!--
window.location.href = "http://www.site.se/script.php"
//-->
</script>
<?php
}else{
echo 'OK : All posts updated within the last : '.$limit.' s';
}
Wget will not run Javascript, if you open your code from the browser, it will of course run it, that is the reason of the difference.
I don't really suggest the method you're trying to use. If you really want, you can call wget again from PHP, use cURL or I guess even header('Location..');. But it would be much nicer to solve this problem in one turn.
If your code times out, I'd recheck the way that PHP code is written, and try to find a better solution, that is not so time-consuming. Afterwards: is the DB good enough, are the indexes set, etc. Or, if you cannot optimize it (or you do not want to), you can use set_time_limit().
(One more thing: Java!=Javascript. If you want to shorten it, write js instead of java)