Best practice for scheduling an event in PHP? - php

What I currently have is a website where admins can create polls. On a poll, they can set a date on when it should end
What I'm aiming to do is on that time that the poll ends, the winner is found (alternative vote method, so a little more work than just tallying up votes) and the status of the poll is changed (this is just a bool)
My current thoughts are to create a cron task when submitting a poll, to be run at the time given. this will just run something like php app/console Poll:FindWinner --my_argument=pollGUID, and my php will find the winner of the given poll and change the status. There could be multiple polls running at once, and possibly multiple dates down the line (eg a date to end the poll on, and a date to display the winner until)
Should a poll be deleted or edited, the cron task would be changed respectively
The only other alternative that I can think of is creating a mysql scheduled event, but I don't think that's a good idea
Is there a better solution for what I'm trying to accomplish? This isn't something that will be run periodically, it must only be done at the datetime provided

Related

Scheduling events in laravel

I want to setup a system for a privileged user to create a new task to run from date/time X to date/time Y saved in MySQL or SQLite? The task will send out a request to remote server via SSH and when the end date/time is up another SSH request would be sent.
What I'm not sure about is how to actually trigger the event at the start time and howto trigger the other at the end time?
Should I be polling the server somehow every 1min (sounds like a performance hit) or setup jobs in Iron.io/Amazon SQS or something else?
I noticed Amazon SQS only allows messages to queue for up to 14 days, how would that work for events weeks or months in the future?
Im not looking for code, just the idea on how it should work.
Basically there are two solutions, but maybe a hybrid version suits your problem best...
Use a queue (build into Laravel) and set up delayed jobs in the queue to be fired later on. You already mention that this might not be the best solution when a task takes months/weeks.
Use a cron job. Downside with this is that you can check once every day but that could mean a delay of 23h59m or you can check every minute but that might give you performance issues (in most cases it kind of works, but definitely not perfect).
Combining 1 & 2 might be the best solution; check in de beginning of a day whether there are tasks going to end in the coming day. If so, schedule a job in the queue to end the task at the exact time at which it should end. This gives you scalability and the possibility to create tasks that end a year after they where created.

Create a MySql job or loop who's constantly checking a field on a table

Well i'm currently developping a browser multiplayers game and having some problem about the conception. This is a Ogame like (http://www.ogame.org/) using PHP / Js / MySql.
What i want is that players will launch an action (cut the wood) and this action will be ending in XX minutes.
So basicely my idea was to create an on the fly cron which will launch after XX minutes a SQL query, adding in the DB XX ressources to the player.
Another problem is that players can navigate on the sea with their ship, so if they are moving to a certain destination they will make XX meter each 5 minutes for example.
So the thing is that all the players can see each others on the sea. So basicaly, i can't wait for 10 minutes to add XX meter to the player ship, it have to be done after 5 minutes...
EDIT : So basicely i need a MySql job like or a infinite loop who's constantly checking on a table. This table will contain the end time (timestamp) of all the actions. And so the job have to execute a Sql Query when this time is corresponding to the CURRENT_TIME.
Hope you guys have understood my problem ;)
What you want is a "job system", or "queueing system", or "event system", or a "message queue".
These can be quite complex to build, but a simple version might just look like this:
You have a database table that just stores a queue of "messages", one message per row, each with some field specifying when it should be handled. Either immediately, or after some timespan, etc.
Your application inserts to this table as-necessary
You have a separate daemon running whose job it is to smartly handle this queue. For example, it pulls down any events that are ready to be handled, based on the criteria you specified when you inserted the event row. Then it handles them. You can run this in a neverending while() loop, and then run the script itself as a background process on your server. If you are handling memory-management well, the script can run forever.
There are a ton of issues with this setup, such as:
What happens if you need to divide up the tasks among multiple servers?
What happens when the daemon processes events more slowly than new ones are getting inserted?
A better solution to avoid these ways is to throw some money at a 3rd party managed message queue service (like Amazon SQS) or use a prebuilt framework that supports this (like gearman). That way you can smartly pull one event at a time from multiple machines who don't really have to care about how backlogged the system is - they just have to happily churn away at events.
Rather than having a specific script run in the future, you could have an events table in your database. So when the user initiates the chop wood task (at say 10:30 AM), you add an event to increment their wood balance by 5 at 10:35 AM.
Then you have a cron script which runs every minute. It gets the current time and looks up the database table for any events with a time that is less than or equal to the current time. You then perform that action and remove the event record from the table. Or if you need to keep a history of these things for your players, you can have a column called processed which tracks whether the event has been performed. In which case your cron script looks for unprocessed events before the current time.

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.

daemon software to update mysql database in background

I'm writing a realtime wep application, something similar to auction site. The problem is that I need a daemon script, preferrably php, that runs in background and constantly launches queries to mysql db and basing on some of criterias (time and conditions from resultsets) updates other tables. Performance of the daemon is crucial. Sample use case: we have a deal that is going to expire in 2:37 minutes. Even if nobody is watching/bidding it we need to expire it exactly in 2:37 since the time it started.
Can anybody advise a programming technology/software that performs this kind of task the best?
Thanks in advance
UPDATED: need to perform a query when a deal expires, no matter if it has ever been accessed by a user or not.
Why do you need to fire queries at time intervals? Can't you just change how your frontend works?
For example, in the "Deals" page, just show only deals that haven't expired - simplified example:
SELECT * FROM Deal WHERE NOW() <= DateTimeToExpire
Accordingly for the "Orders" page, a deal can become a placed order only if time hasn't expired yet.
Does your daemon need to trigger actions instantaneously? If you need a table containing the expired state as a column you could just compute the expire value on the fly or define a view? You could then use a daemon/cron job querying the view every 10 minutes or so if you have to send out emails or do some cleanup work etc.

How can I trigger events in a future time in 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.

Categories