Making timers to run code on expired records - php

I am developing a web application (PHP/MySQL), in which I need to implement timers (record id expires at expiration_date), where expiration involves the record's state being updated and arbitrary code being executed as required.
I basically need a BPMN Timer event.
Options I have considered, none of which I am thrilled with:
Cronjob calling a function in the application that just queries for and updates expired records.
At a commonly called point in the code, call this function at a fixed interval.
How is this commonly done in PHP applications?

The following is an option which you have not considered:
You could use MySQL Event Scheduler to run a stored expiration routine within the database periodically.
Some good things about this approach:
Platform independent, works the same way on UNIX and Windows.
Easy to set-up. No need to explain to the user how to setup cron jobs. You just create the event together with your database schema.
Downsides:
Not enabled by default in MySQL. Need to put event_scheduler=on in my.cnf or otherwise enable it.
Requires MySQL 5.1 or newer if I remember correctly.
Example:
DROP EVENT IF EXISTS expire_event;
DELIMITER //
CREATE EVENT expire_event
ON SCHEDULE EVERY 1 MINUTE
DO BEGIN
DELETE FROM data WHERE time < UNIX_TIMESTAMP(NOW() - INTERVAL 1 HOUR);
END //
DELIMITER ;
The above will every minute delete any rows from data table which have a UNIX time stamp older than 1 hour.

I would also choose the cronjob option.
I would also, however, have logic in my app that knows how to deal (or ignore) expired records. Services like cron can break, so it's nice to NOT have to rely upon it.
Unfortunately, DBMSs don't give us quite this sort of flexibility, and you won't want to go off and do database maintenance in the event you come across one of these "expired" records.
You're best excluding them through queries, the use of views, or simple application logic.

I would choose the cronjob option.

Related

Automatically change database row item if it has not been changed within a certain time

I'm having a hard time on creating a time allowance for reservations in PHP. I did research regarding this but unfortunately I do not know what are the exact terms for this.
I already have a working reservation module, I need to add a feature that automatically cancels that reservation within 30 minutes if it is not confirmed by the client.
Is there a PHP code fragment where it will automatically set the value of a row if it has not been changed within 30 mins?
PS: Sorry for bad english.
Is there a PHP code fragment where it will automatically set the value of a row if it has not been changed within 30 mins?
No. This is data-centric, presumably your "reservation" is stored in a database (e.g. MySQL)?
PHP as a platform is in 99.9% of scenarios responding to a request (either CLI or HTTP) - or so called "event driven". There is no easy way to create an "event" for something expiring in the future without moving your mind beyond pure PHP.
You can be event driven in your updating of an "updated at" field by using your DBMS' timestamp (e.g. see ON UPDATE CURRENT_TIMESTAMP()) from which you can check (on any future event) whether the record has "expired" (last updated timestamp + 30 minutes).
If you need to generate an event when expiry occurs (e.g. send an email to say the reservation was cancelled), unless you have some sort of 'deferred execution' (a feature of some queuing platforms - outside the scope of this answer) you will need to periodically poll (the "kind-of" opposite to event driven) to find any records which have expired.
The most common means of doing that through PHP on a LAMP stack is by writing a cronjob. That's a forever-running service which will (with a maximum frequency of every 60 seconds) trigger your code.
If you're heading down the polling route but only need to manipulate date (no email sending etc), you could investigate using your DBMS scheduler (e.g. MySQL events). A word of warning though - hiding business logic inside the database doesn't always lead to maintainable solutions.
Added note: If you're not already using a PHP framework, consider discovering the joys of products like laravel which give you task scheduling out of the box.
I would suggest another approach:
one of these 2 ways:
1) when checking open reservations, always add the check WHERE createdat > NOW() - INTERVAL 30 MINUTE.
that way you will only see the reservations that still can be confirmed
Note that 30 minutes is now hard coded in the query /queries
2) when the time can vary, you could also consider adding an extra column to you table: expiresat
When inserting your reservation, you can write the moment until the reservation will expire:
INSERT INTO table (all, columns, expiresat) VALUES ('all', 'values', NOW() + INTERVAL 30 MINUTE)
this way you could vary the number of minutes per order, or give people at night more time fi.
When confirming, you can reset the value of this column to null
And you have to modify the queries with:
WHERE expiresat > NOW() OR expirexat is null
It is more effort in the programming side, but you do not have to worry about processes always having to run to remove open reservations

how to reset a sql field after a timeout

So I have a particular field in my database table which I would like to reset to 0 after a fixed period of time, like e.g 1 week. MY language is php. Is there any way to do it? Please help me
Okay, so basically I have a column "activation points". These points increase whenever a user does some sort of activity. But I need to reset the points to 0 every week
There is no really nice way to do this with PHP.
You have a few options:
Use MySQL's newly added, built-in, scheduler: Event Scheduler.
Use software from sources other than PHP or MySQL, like cron jobs.
Use a PHP library like PHPScheduler which isn't a true scheduler.
Option 1 is probably your best bet. It is built into MySQL, and you don't have to worry about messing with any other software that you aren't already using.
Option 2 is easy to implement, but does involve using another tool other than just PHP and MySQL. You can learn how to set up cron jobs with this post.
Option 3 is not recommended by me, unless you just absolutely want to use PHP to do this. But you will be limited on the customization of the scheduling. PHPScheduler isn't technically a true scheduler, and you can read why in this post. That post linked is older though, so it will mention that there is no scheduling available in MySQL, but since that post was made, Event Scheduler has been made.
To use Event Scheduler (Option 1), you should refer to this really really good tutorial and if you have any problems, this documentation.
Here's a preview of how easy it is to use Event Scheduler:
CREATE EVENT nazzus_cool_event
ON SCHEDULE EVERY 1 MINUTE
STARTS CURRENT_TIMESTAMP
ENDS CURRENT_TIMESTAMP + INTERVAL 1 HOUR
DO
INSERT INTO messages(message,created_at)
VALUES('Nazzus cool event just happened again!',NOW());
This code will create an event called nazzus_cool_event, and it will occur every 1 minute(s) starting at CURRENT_TIMESTAMP (now), and ending an hour from now. It will insert some data into the messages table.
It's very simple but you should definitely have a quick look at this great tutorial so that you can see some more of its great features.
You can write a simple mysql statement that will updated your field to 0 and put it on cronjob that will run every week.
edit:
Make sql statement that will reset your column, put it in php file and call it on cronjob, you can check it here , you can always use some free online solutions for cronjob like this one

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