I'm trying to create a computer reservation system, where user chooses a computer and select the time how long he will be using this PC. In that time other persons can't reserve this pc, I need to find a solution, how to automaticaly delete all rows containing reserved pc's after their time expires. Thank you for the advice.
The common way to handle this is to store an expires_at timestamp on the reservation row. Then your query to find any "open" reservations would have WHERE 'expires_at' < NOW() or something similar.
This is an untested answer, that may only be a suggestion, but I just started looking at these, so am interested in feedback as well. i'm still working through possibilities and drawbacks, but it might well suit your need.
Take a look at MySQL Events, an article about it is here, and official syntax at Mysql Docs.
Per the article:
An event is similar to a trigger. However, rather than running in
response to a data change, events can be scheduled to run any number
of times during a specific period. In effect, it’s a database-only
cron job.
Pondering this, I'd envision a procedure that deleted anything >1hr (if that's the expiration). This procedure would be TRIGGERED on new inserts to get rid of anything expired at that moment, but also in an event to run every 15 minutes or so so that automatic deletes by the trigger aren't dependant on somebody else adding a reservation to trigger that procedure.
If your server is linux, you can use cron jobs to check once a day every reservation dates. If these dates have expired .. modified field reserves to be available.
Normally I would do it this way:
when storing a reservation, store date_from and date_to both of datatype DATETIME
when checking if there is a computer free check for all computers and filter with WHERE '{$my_date}' >= date_to AND '{$my_date}' <= date_from - by this You should be able to get all the PCs that are not reserved within a certain time...
To be complete in the solution, you need to run a CRON job which calls a query to remove all reservations that have a reservation_time + (15 * 60) < unix_timestamp().
I am assuming you have a time that the reservation was placed or started and are using UNIX/Epoch Timestamps.
Instead of doing a expires_now, if you know it will always be a fixed interval ie 15 minutes, you can do:
DELETE FROM reservations WHERE reservation_time + (15 * 60) < unix_timestamp()
Something you could look into is managing cron job's from PHP, http://www.highonphp.com/cron-job-manager.
The above script will, when a reservation is created, insert an entry into /etc/cron.d/ and you could configure it to run at the expected reservation endtime. Then inside the php file which would be executed, you could do:
DELETE FROM reservations WHERE id = :id
Related
I would like to store events' recurrences in a mySQL database (additionally, I'm working with Symfony 3 and Doctrine ORM).
For instance:
Every 3 days / Once a week / Bimonthly / Half-yearly / Once a year
What is the best way to store this kind of data in order to be able to easily perform queries on it?
Moreover, I want to create complex reminders based on these recurrences.
For instance:
From February to September: once a week and from October to January: bimonthly
How could I manage reminders' dates calculation? Should I store the start date and calculate the next dates each time, or should I store only the next date when a reminder is marked as completed?
(My use case: set reminders for watering plants).
Thank you a lot for sharing what do you think about!
Regards!
You can set events in MySQL itself or as pogeybait suggests, you can write a cron job and a command.
If you need the server to do something outside of the database, you likely need a cron job. If it's all contained within the database (such as just updating a "plants_need_watering = false" column to "plants_need_watering = true" without having to send an email or start some other program) then I'd say MySQL events are more suitable.
Here's a pretty good tutorial on events (although, I had to play around with the delimiters when I tried it): https://www.sitepoint.com/how-to-create-mysql-events/
Here's a simple event I wrote. You can see how it just updates a db column based on the date. I set the status of a my own "event" (not a MySQL event, but an entity from my application) to "Voting is closed." if the "voting_end" date is past today and this runs every 12 hours so I know I can't accidentally miss one. This is just entered once as regular SQL, you can practice and check results on a local dev machine by setting the schedule to every hour or so, check to see that it worked, then switch back to the actual desired timeframe to run the event: every week, every month, etc.
SET GLOBAL event_scheduler = ON;
CREATE EVENT switch_event_status
ON SCHEDULE EVERY 12 HOUR
DO
UPDATE event_status
INNER JOIN
event ON event_status.id = event.event_status_id
SET
event_status.value = \'Voting is closed.\'
where
event.voting_end <= cast(now() as date);
Also, here's the Symfony documentation on writing console commands. It's actually pretty easy. http://symfony.com/doc/current/console.html
And cron jobs to kick the console command off: https://www.cyberciti.biz/faq/how-do-i-add-jobs-to-cron-under-linux-or-unix-oses/
If you are on a Linux machine, you can use cron jobs to check however often as you'd like. Id create a console app to do this so the cron job is easier to call. It's easier than you think to create the console apps. For the database I'd store general info about each event (name, title, description) and an interval field which would say how often that even should trigger an notification. Initially store the current date and time when the event is added and then when the interval time passes trigger then notification and store the date and time of the notification. That's the simplest way I can think of. See more here http://symfony.com/doc/current/components/console.html for console commands.
I need to delete particular info from data base using only php, after some time without using cron system. How can I realize it?
Without cron there is only one way i.e hook that deletion code with some event e.g login of any user. As a new user logs in you can run that code
Include a timestamp in the database table. Then have a function in your PHP that deletes all records that are more than X minutes old whenever the PHP is run.
You can use a query such as this (for all records more than a day old).
DELETE FROM `table`
WHERE `timestamp` < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 DAY))
So, I've done quite a bit of googling on this topic, and I just can't find an answer. So, basically, I'm looking to make a small website, that will pull information from a HTML form, send it to a database, then after two hours, it will automatically delete itself. I have a basic theory on how this could work, but I can't figure out how to do it: I could pull the current time and date, add two hours to that, then put the time into an "expires" column in the database. Once the time is the one that is in the expires column, the data will be removed from the database. Sorry if this is a very "noobish" question, I'm still a bit new to databases with PHP.
Anyway, any help would be much appreciated! Thanks!
You could add a new timestamp column to your table which will automatically add the timestamp of when the row was created like so
CREATE TABLE t1 (
#your existing columns defined as before + this new column
ts_created TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Now every time you create a row on this table, MySQL does all the work of recording when it was created.
Assuming you may not be able to create a cron job on your host you could then add the deletion code in the most obvious place in your existing site code to do the removal.
// remove old stale data
$sql = "DELETE FROM user
WHERE ts_created < DATE_ADD(NOW(),INTERVAL -2 HOUR)";
if ( ! $mysqli->query($sql) ) {
// log $mysqli->error somewhere
}
ALthough a cron job seems a good idea at first sight, in order to make sure things are always accurate on this table you would have to run it every 30 seconds or maybe even more often. That would get in the way of other activities on this table, if the site was busy that could be a problem, if it was not busy you would just be running the cron unnecessarily most of the time.
If you add the deletion code just before you present this information to the user at least it would only be run when required and you would also ensure that the table was always accurate at the time the data was presented to the user.
You can ensure the scheduler starts when MySQL is launched with the command-line option --event-scheduler=ON or setting event_scheduler=ON in your MySQL configuration file (my.cnf or my.ini on Windows).
Run this query statement in mysql
SET GLOBAL event_scheduler = ON;
Create an mysql event scheduler using following - this will behave like Cron Job but actually it is a mysql trigger on specific interval. This is triggered from mysql server.
CREATE EVENT e_hourly
ON SCHEDULE
EVERY 1 HOUR
COMMENT 'Clears out sessions table each hour.'
DO
DELETE FROM table_name WHERE UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(remove_time) > 120
http://dev.mysql.com/doc/refman/5.1/en/create-event.html
http://www.sitepoint.com/how-to-create-mysql-events/
Pardon my explaination - I myself have implemented this just now and it worked.
Just add a column remove_time (DATETIME) and set the time you want the row to be deleted. Than use cron (configuration depends on webhosting you have) to run this query (probably as poart of PHP script):
DELETE FROM table WHERE remove_time <= NOW()
You can configure cron to run every minute (or less/more, depending on your needs).
Try implementing a cron which will run at specified time automatically to check and delete the rows whose created_at is less than the current_time by 2 hours.
On how to implement cron, check Skilldrick's answer here
Thank you
:)
As the title reads, I am looking for a way to update a mysql field after 10 minutes has elapsed of a query being run.
Something like below is an example without the time restraint:
mysql_query("UPDATE `players` SET `playcoins`=TRUNCATE(ROUND((`playcoins`+$amount),9),8) WHERE `id`=$player[id] LIMIT 1");
Any ideas?
MySQL databases have a class of object called an EVENT. It's basically a hunk of SQL code that runs at particular time, or on a particular interval.
You could use code like this to create an event to do what you require at the right time in history. This particular code will create an event that runs just once, ten minutes in the future.
DELIMITER $$
DROP EVENT IF EXISTS coins_user12345$$
CREATE EVENT coins_user12345
ON SCHEDULE
AT NOW() + INTERVAL 10 MINUTE
ON COMPLETION NOT PRESERVE
ENABLE
DO BEGIN
UPDATE players
SET playcoins=TRUNCATE(ROUND((playcoins+123),9),8)
WHERE id=12345
LIMIT 1;
END$$
DELIMITER ;
To use these EVENT objects, you have to configure the event scheduler correctly. Read this. http://dev.mysql.com/doc/refman/5.6/en/events-configuration.html Some cheap shared hosting providers don't allow the use of events, so this is not guaranteed to work.
You go it the wrong way. Sure you can do it. And you can do it with PHP. But you shouldn't. PHP is not the right language to do such a task. Before I starting talk about shell_execute and sleep, which would be the core elements, you need to do this, I offer you another solution.
If I see right, you want to give a player every 10 minutes, some coins.
The right approach would´basicly be:
Save the last time the player has get coins in the database. If you get the player coins, you first want to check, the last time you give the player coins. Now calculate, how much he has earned in this time difference. Finaly add this to his balance and update the field, where you save the last time, the player has earned coins.
An alternative would be a Cronjob/Scheduled Task to a PHP file, which is called every 10 minutes, to give each player the coins, he should get.
I want to make a table where the entries expire 24 hours after they have been inserted in PHP and MySQL.
Ideally I want to run a "deleting process" every time a user interacts with my server, that deletes old entries. Since this is more frequent you should it will not have large amounts of data to delete so it should only take a few milliseconds.
I have given each entry a date/time added value.
How would I do this?
You could use MySQL's event scheduler either:
to automatically delete such records when they expire:
CREATE EVENT delete_expired_101
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 24 HOUR DO
DELETE FROM my_table WHERE id = 101;
to run an automatic purge of all expired records on a regular basis:
CREATE EVENT delete_all_expired
ON SCHEDULE EVERY HOUR DO
DELETE FROM my_table WHERE expiry < NOW();
you shouldn't do a delete process when a user interacts. it slows down things, you should use a cronjob (every minute / hour)
you'll want to index the added timestamp value and then run DELETE FROM table WHERE added < FROM_UNIXTIME(UNIX_TIMESTAMP()-24*60*60)
maybe you'll want to checkout Partitions, which divide the table into different tables, but it behaves as one table. The advantage is that you don't need to delete the entries and you'll have seperate tables for each day.
i think that YOU think that much data slows down tables. Maybe you should use EXPLAIN (MySQL Manual) and optimize your SELECT queries using indexes (MySQL Manual)
UPDATE Check out eggyal's answer - This is another approach worth taking a look.
You can look into using Cron Job, http://en.wikipedia.org/wiki/Cron Make it run once every 24 hours when it matches your requirement.
This will help
Delete MySQL row after time passes