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.
Related
So here is what I am trying to accomplish:
User selects how often they want their post to be moved to the top of the page, whether it be every 30 minutes or every hour or every 2 hours, etc. They will be able to select how many times that it will do this. So if they select it to update every hour for 5 hours, it will then update the date/time in the database to the current time and then updates that time every hour for the next 5 hours and cancels it after the 5 hours are up.
I was thinking of running a PHP script like this to update the table since the ads are displayed by date DESC:
<?php
//cronjob.php
$id = $_SESSION['ad_id'];
$date = date('Y-m-d H:i:s');
$query = "UPDATE ads SET ad_date = :date WHERE ad_id = :id";
?>
Is there a best way to do that or will a CRON job that is selected by the user going to be too much load on the server to have users setting up CRON jobs continuously.
I saw this one approach and wonder if it is possible to set it up for this purpose. I am still getting familiar with CRON jobs.
How to start/stop a cronjob using PHP?
I will be setting this up on Godaddy's server:
Godaddy Cron jobs
Appreciate the help.
One method is to store the required updates in a new database table, containing fields such as the post id, how many times to update, interval, how many updates are left, the time at which the first update should take place ( or the time for next update ) .
Then, create a php script that fetches data from this table and take necessary action for each post. Check if it's time to update the post, if yes then update, else don't ( check time with accuracy upto minutes, don't check seconds. If you can, do this time checking with SQL and not in php to reduce the data being fetched ). It's better to perform all updates in a single query to maximise efficiency.
Then set up a cron job on the server that runs this php script every minute or whatever minimum time interval you need.
This way, you can get away with just one cron job😉
If you need even more efficiency, then at the end of this script, check if there are any more updates pending, if none then delete the cron job. Then, set up your code such that whenever a user creates a new update, check if the cron job exists, if it doesn't then create it ( this additional dynamic cron job is only for efficiency freaks. If there are frequent update requests, it might be better to avoid creating/deleting cron jobs )
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 am creating a system that requires a schedular for a particular task. Users may pick from times 24 hours a day, 7 days a week.
I came up with a few options for the database storage, but I don't think either one is the most efficient design, so I'm hoping for some possible alternatives that may be more efficient.
On the user side I created a grid of buttons with 2 loops to create the days, and the times, and I set each a unique value of $timeValue = "d".$j."-t".$i;
So d1-t0 will be Saturday at Midnight d3-t12= Tuesday at Noon, and so forth.
So, in the database I was first going to simply have a ID, day, time set up, but that would result in a possible 168 rows per event
Then I tried an ID, day, and time 0-23 (a column for each hour of the day) And I was simply going to have a boolean set up. 0 if not selected, 1 if it is.
This would result in 7 rows per event, but I think querying that data might be a pain.
I need to perform a few functions on this data. On each day, list the number of selected times into an array. But I don't believe having a select statement of SELECT * from schedule where time0, =1 or time1= 1 .... ect will work, nor will it produce the desired array. (times=(0,3,5,6,7...)
So, this isnt going to work well.
My overall system will need to also know every event that has each time selected for a mass posting.
"Select * from table where time = $time (0-23) and day= $day (1-7)
Do action with data...
So with this requirement, I'm going to assume that storing the times as an array within the database is likely not the most efficient way either.
So am I stuck with needing up to 168 rows of data per event, or is there a better way I am missing? Thanks
Update:
To give a little more clarity on what I need to accomplish:
Users will be creating event campaigns in which other users can bid on various time slots for something to happen. There will likely be 10-100 thousand of these campaigns at any one time and they are ongoing until the creator stops them. The campaign creators can define the time slots available for their campaign.
At the designated time each day the system will find every campaign that has an event scheduled and perform the event.
So the first requirement is to know which time slots are available for the campaign, and then I need the system to quickly identify campaigns that have an event on each hour and day and perform it automatically.
I'm redeveloping my online text based MMO, And I'm building a "Travel" Script Where a user clicks where they want to go and it takes X minutes to get there.
The only problem is - Due to limitations of my host, I cannot run 1 cronjob every minute to take away time spent travelling.
Can someone tell me how i could achieve this without using crons? Delaying a query from being run for multiples of 1 minute or so?
Once they set off, A countdown from that moment of X minutes begins, And once their travel time reaches 0 their "location" is set to "destination"
Thanks!
Use PHP sleep() method.
Like sleep(60); will result in the script to wait execution for 1 minute.
Do NOT set a script timeout as it wont make any sense.
I suggest you add a destination time column, set it to when the animals should arrive, and then in the client display a countdown until that time. You could use a query such as
select * from arrivals where arrival_time < now();
To get a list of animals that have not yet arrived, and of course the arrival_time is when they will arrive.
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