How can I trigger events in a future time in PHP - php

I have written a PHP application that broadcasts a voice message to phone numbers in the database.
Now I want to add a "Schedule" functionality to it.
It basically means that the administrator would be able to set a future date and time for a particular voice file. The voice messages will be broadcast at exactly that date and time.
How can I code this please?
Some code snippets will be highly appreciated.
Thanks,
Amit

You need to look into CRON jobs to automate script execution automatically. Take a look at: http://net.tutsplus.com/tutorials/php/managing-cron-jobs-with-php-2/ for some more info.

As Tom Walters says, cron (or Scheduled Tasks if you're using windows) is probably a good way to go (at least at first).
Cron's maximum resolution is 1 minute, so hopefully, that's precise enough.
Consider a table like:
create table calls(
id int,
target_time datetime not null,
actual_time datetime default null
-- plus whatever data are necessary
);
Then you write a script that does the following:
Queries the database for all call with target_time <= the current
time, where actual_time is NULL. (Something like SELECT * FROM
calls WHERE actual_time IS NULL and target_time <= NOW())
Iterates over those calls, making the calls, and updating the row to
set actual_time as it goes.
Then, you use cron (or whatever) to run that script every X minutes.
That's a basic architecture that should get you going.
Of course, things get more complicated if you have multiple lines for outbound calls, or other fancy requirements.
If you require accuracy approaching seconds, cron is going to fall short. At that point, you might consider writing one or more daemons (scripts that run continuously) to poll the database more frequently.

Related

Triggering code at a certain time

Is it possible to tell PHP to execute a piece of code on a given date and time? For example, Blogger.com allows someone to set a blogpost to be published in the future (e.g. 12/12/14 6:00AM).
Can PHP do something similar?
(Sorry, I don't even know what the correct term for events like these would be to be able to even search for them! :( )
You can do this using a cron job (or scheduled task on Windows); although they are typically used for reoccurring jobs.
If you're using a database, most platforms come with a scheduler.
You can schedule your action in your database and use a cronjob on your server or use a cron job service To run your actions.
https://www.setcronjob.com/
For example when you want to publish your blog in the future, you save your publish date in the future and set some sort of auto-publish bit.
Then every hour a PHP script is ran by a cronjob, this script checks the database for all blogs which need to be published.
It's not possible to tell PHP to do this itself, since it would require a process to run forever to periodically call your PHP code. Thankfully though, there's a couple of things which do this:
1) Call a PHP script from a cron job, which then does any necessary work. If you don't have access to a crontab, you can periodically call this when a user pings your site instead, although that will be less reliable, of course.
2) Use at. This works in basically the same way as cron on Linux systems, but will schedule once and at an exact time.
for "triggering code at a certain time", cron works. But for something as simple as publishing an article at a specific time, it isn't needed. You can just store a publish date with your article. When displaying a list of articles you can adjust your query to something like WHERE PUBLISH_DATE <= NOW() and on the article page check if the article's publish date has passed before showing the article.
On Unix-like systems, there's Cron. You can manage Cron from PHP.
On Windows, there are scheduled tasks - you can also use PHP to manage scheduled tasks.
Be careful with this though - it's kinda hard to test, and you may end up with a schedule that cripples your server.

Resent mysql values at certain time

I have a database with a table and some columns. One of these columns is flags (similar to SO) where users can flag comments. I would like to give each user 5 flags per day. So if a user uses 2 flags in a 24 hour period, the flags should reset to 5 at the end of the 24 hours. I really have no idea how to do this. Is there a special mysql function?
PHP:
$query=mysql_query("UPDATE users SET flags='5' WHERE userID='$user'");
how would i get this to repeat every 24 hours? (if this is the right solution)
The best way is probably to set up an automated task (possibly using cron) that runs a query to do this.
Make a script and add to cron job. It will automatically update all on specified time of day.
Cron is very simply a Linux module that allows you to run commands at predetermined times or intervals. In Windows, it’s called Scheduled Tasks. The name Cron is in fact derived from the same word from which we get the word chronology, which means order of time.
Using Cron, a developer can automate such tasks as mailing ezines that might be better sent during an off-hour, automatically updating stats, or the regeneration of static pages from dynamic sources. Systems administrators and Web hosts might want to generate quota reports on their clients, complete automatic credit card billing, or similar tasks. Cron has something for everyone!
You can use MySQL Event Scheduler and define an event to let it update every interval you want.

Execute script at variable time

I'm aware of cron jobs to execute commands at a certain time, but what if that time is not constant? For instance, suppose a user asks for a reminder email exactly 1hr after signing up for something, is there an easy way to go about doing this?
Timing is critical. I am actually trying to create AI that will essentially act on its own but only at variable points during the day. Any help would be appreciated!
You can use at to schedule jobs for specific times. cron is for repeating jobs, at is for one-shot/oddball interval ones. Both have a resolution of 1 minute, though, so you can't specify a start period with seconds granularity.
The command's available on both Unix/Linux and Windows.
Here a workable flow:
user Requests email in 1 hour
You insert into the a table action (action_id, time)
On the PHP server create a cron job to check the action in the action table every minute, then do the action that need to be done at that time
That is a simple example from the request. It might get a bit more complex then that.
EDIT : this suggestion might be good only if you need to be very precise with the time management!
if you dont wanna use the cron triggers and you are not comfortable with them here are two php scheduling libraries..
1) http://www.php.brickhost.com/
2) http://www.phpjobscheduler.co.uk/
Try them if you like:

PHP and mySQL Task Scheduler program and database theory?

I need to develop a website that runs jobs at certain times (every 15 minutes) I'll use a cron to run the webpage.
What is the best way to store the jobs information in? Some jobs will be daily, others every 8 hours etc. To complicate matters, I also need to take into consideration the timezone differences. This shouldn't be too difficult as PHP has many timezone functions, but how do I integrate it in the programming of the next job to run?
Another question, is how will the user enter the information for the jobs to run? One option, similar to http://www.webcron.org, is to ask the user to select how often the jobs must run, but how do I store that info in a database?
Any assistance will be greatly appreciated!
I would use the crontab syntax, store it in a DB and run a separate crontab invoking the execution script every minute.
There are GPL classes that do that for you already, like : http://www.phpclasses.org/package/4140-PHP-Database-driven-PHP-job-scheduler-like-cron.html
Create a MySQL Event, that will take care also the storing, recurrence, execution.

Should I be using message queuing for this?

I have a PHP application that currently has 5k users and will keep increasing for the forseeable future. Once a week I run a script that:
fetches all the users from the database
loops through the users, and performs some upkeep for each one (this includes adding new DB records)
The last time this script ran, it only processed 1400 users before dieing due to a 30 second maximum execute time error. One solution I thought of was to have the main script still fetch all the users, but instead of performing the upkeep process itself, it would make an asynchronous cURL call (1 for each user) to a new script that will perform the upkeep for that particular user.
My concern here is that 5k+ cURL calls could bring down the server. Is this something that could be remedied by using a messaging queue instead of cURL calls? I have no experience using one, but from what I've read it seems like this might help. If so, which message queuing system would you recommend?
Some background info:
this is a Symfony project, using Doctrine as my ORM and MySQL as my DB
the server is a Windows machine, and I'm using Windows' task scheduler and wget to run this script automatically once per week.
Any advice and help is greatly appreciated.
If it's possible, I would make a scheduled task (cron job) that would run more often and use LIMIT 100 (or some other number) to process a limited number of users at a time.
A few ideas:
Increase the Script Execution time-limit - set_time_limit()
Don't go overboard, but more than 30 seconds would be a start.
Track Upkeep against Users
Maybe add a field for each user, last_check and have that field set to the date/time of the last successful "Upkeep" action performed against that user.
Process Smaller Batches
Better to run smaller batches more often. Think of it as being the PHP equivalent of "all of your eggs in more than one basket". With the last_check field above, it would be easy to identify those with the longest period since the last update, and also set a threshold for how often to process them.
Run More Often
Set a cronjob and process, say 100 records every 2 minutes or something like that.
Log and Review your Performance
Have logfiles and record stats. How many records were processed, how long was it since they were last processed, how long did the script take. These metrics will allow you to tweak the batch sizes, cronjob settings, time-limits, etc. to ensure that the maximum checks are performed in a stable fashion.
Setting all this may sound like alot of work compared to a single process, but it will allow you to handle increased user volumes, and would form a strong foundation for any further maintenance tasks you might be looking at down the track.
Why don't you still use the cURL idea, but instead of processing only one user for each, send a bunch of users to one by splitting them into groups of 1000 or something.
Have you considered changing your logic to commit changes as you process each user? It sounds like you may be running a single transaction to process all users, which may not be necessary.
How about just increasing the execution time limit of PHP?
Also, looking into if you can improve your upkeep-procedure to make it faster can help too. Depending on what exactly you are doing, you could also look into spreading it out a bit. Do a couple once in a while rather than everyone at once. But depends on what exactly you're doing of course.

Categories