Automatized action on scheduled date in MySQL - php

I need an action to be realized automatically when a specific date is reached in a MySQL database, so not necessarly when a user is logged in the site and does an action.
This would go for many different entries in the table.
For example, when UTC_TIMESTAMP() reaches 'release_date' for different items, a PHP script would be executed, respectively for each items.
This is something I have never approached before.
I'm reading about Cron Job and MySQL EVENTS. Would that be the way to go?
Thanks in advance! Any help is greatly appreciated.
Lois

The best way to do this is to have a cron job that runs every time interval, you have full control of how often the script will run,
Within this script, you'll basically check the current time and see if it hits your 'release_date', then you run some queries against your db, if not, the script just exits.
so you can create a cron entry that runs every hour, like this
00 * * * * /usr/local/bin/php /path/to/script.php
and inside script.php
#!/usr/bin/php
$release_date = 1383135371;
$now = time();
if($now >= $release_date){
//Connect to database and do your code here
}
This way you'll have much more control of how things will work, this is not even scratching the surface of the powers of cron jobs !, let us know if things aren't clear :)

What you can do is create a PHP script that would run your query, do your comparisons, and then run the appropriate scripts. You would then run this script from the command line via cron. Here's a page that describes it in more detail
http://www.thegeekstuff.com/2011/07/php-cron-job/

Related

Reading crontab-like syntax from a database to execute functions

I have a database of scheduled tasks that'll be run based on the normal crontab-like syntax eg. min hour dom month dow (in separate table fields).
I'm not all that good at explaining myself, however what I would like to do is just set up one actual system crontab every minute, then that PHP file will then parse my database to look for all the scheduled tasks with crontab syntax, then when it hits the right time/day/etc, execute a function..... So, for example, if I set */10 for the minutes, then * for the rest, the function should be executed every 10 minutes, checked from the every minute running system cron.
To be honest, I am not sure how I go about actually parsing the database crontab-like syntax via PHP - like, take the example I just give, every 10 minutes. I know I'd need to record the last timestamp of the said task was run and the next timestamp it will be run - however, it's just initially working out when this next timestamp will be based on the crontab syntax I'll have issues with.
Hope I have explained this clearly, and thanks in advance.

How to delete mysql row after time passes?

I have no idea where to start with this one:
I have a database that stores postID and Date.
What I want to do is have my website auto delete all rows where Date is less than today. This script can't have any user input at all. No button clicks, nothing. The script must run every day at midnight.
I've been looking all over the place for something that does this and I've found absolutely nothing.
You can use PHP script and use cron job on your cpanel.
Example:
cronjobcommand.php
<?php
include 'your_db_connection';
mysql_query("DELETE FROM your_table_name WHERE Date < NOW()");
?>
I have attached a screenshot below for your more reference.
For those out there who are on a shared hosting, like 1and1's, and can't use cron, here are 2 alternatives :
mysql events enable you to place a time trigger on mysql, which will execute when you'll want, without having to be fired by any kind of user input
if you cannot create mysql events because you're on 1and1 :(, an alternative is to use webcron
You just need to tell webcron the url of the php script you'd like to be run, and they'll trigger it for you at the intervals you want
Why using cronjobs everyday?? Why not filter data on output. For example in your select check if post date equals today with adding a simple where:
SELECT * FROM `posts`
WHERE (DATE(`post_date`) = DATE(NOW()));
This way you're not required to do your database managements/cronjobs on any special time and it will be used just for database managements. Afterwards you can delete unnecessary data at any time using by mysql command like:
DELETE FROM `posts` WHERE (
DATE(`post_date`) < DATE(NOW())
)
Most hosts provide a cron(8) service that can execute commands at specific times. You use the crontab(1) program to manage the crontab(5) file the describes when to run which commands.
There's a lot of functionality available to you, but if you write a program (shell script, php script, C program, whatever) that runs the appropriate MySQL commands, you can call the program via cron(8) in an entirely hands-off fashion.
Run crontab -e to edit your current crontab(5) file. If none exists, hopefully you'll get one with a helpful header. If not, copy this:
# m h dom mon dow command
The columns indicate the minute, hour, day of month, month, and day of week to execute commands. All the numbers in the columns are essentially ANDed together to decide when to run commands.
Thus, midnight every night would look like this:
0 0 * * * /path/to/executable
It's remarkably flexible, so put some time into the documentation, and you'll find many uses for it.
You should set cron job (scheduled tack.) for it.
A cron job is an automated program setup for Linux and Unix operating systems. It allows the user to execute several commands or functions at a specific time and date.
you have cron Job in your cpanel setup. first you need to make a php script with your logic for delete record after each date. take date from server and write script for delete.
then go to cron tab in your cpanel and do settings for time interval to run cron and give path of your php script file.
MySQL doesn't have a task scheduler. So you have to use the task scheduler of your Operating System (CRON under Linux), or to lunch a basic task checker sub-script during the script of the main page (on another page that is supposed to display the changing data).

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: execute script 5 minutes after first script is run

I'm making a PHP site, and I would like to have a script (when you click a button) which adds some info to my MySQL database (I can do this part by myself) and it executes a script 5 minutes later. Maybe it's not difficult, but it's hard to google stuff like this.
Sleep is a VERY bad idea. Client browser would have to wait 5 minutes to finish request!!!
In my opinion it's not possible to do it like you want to.
You should create another script which queries database and checks if there is new data (and on successful fetch does the job). This script should be run by cron every N minutes.
Pretty tough one.
I'd go for something like this:
your original script adds a record to the database, containing its time of execution,
another script contains the action that needs to be taken 5 minutes later - but launches it only if the db record mentioned above contains a timestamp of at least 5 minues ago (hope that's clear enough, I'm having trouble phrasing this)
set crontab to execute the second script every X minutes (perhaps 2).
It won't be 5 minutes EXACTLY, but rather something between 5 and 7 (in case you choose to launch the script every 2 minutes). Would that do?
You could implement a queue in your database, where you add "commands" to be executed, and also store when to execute this command. Then have a cron job that runs every minute and checks said queue to see if it's time to execute a certain command.
If you're on a unix box:
exec("echo 'php script.php' | at now +5 minutes");
Which will schedule the php script.php command to run after 5 minutes.
I'm making a browser-based game and I want it to if someone wants to build a building it takes * minutes and then finishes.
Considering this is your actual goal, I recommend just saving the original building with a timestamp.
I know you tagged your question with PHP, but I don't want to include all the overhead of handling mysql queries in PHP, especially since I don't know how you prefer to execute the queries or what framework you're suing, so here's some pseudocode to handle this "building buildings" task:
build.php
building_type_id = sanitize(POST['id'])
user_id = current_user['id']
query('INSERT INTO buildings (user_id, building_type_id, created_at)
VALUES (' + user_id + ', ' + building_type_id + ', CURRENT_TIME)');
my_buildings.php
user_id = current_user['id']
completed_buildings = query('SELECT * FROM buildings b
LEFT OUTER JOIN building_types t ON b.building_type_id = t.id
WHERE DATE_ADD(b.created_at, INTERVAL t.construction_time SECOND) < NOW();')
under_construction = query('SELECT * FROM buildings b
LEFT OUTER JOIN building_types t ON b.building_type_id = t.id
WHERE DATE_ADD(b.created_at, INTERVAL t.construction_time SECOND) > NOW();')
Hope this helps!
IMHO the best way is: On button click save the job to run in the db with the time it should run. Write a small daemon, fetches every 10/5/2 seconds new jobs which should be executed and executes them.
EDIT: Btw the idea using cron for checking for new jobs to execute, is better, but only if you have a small website and you don't need to do load balancing for the jobs.
The way I would do this is to run a cron job between the two scripts.
the first script sets a value in a database table.
the cron job executes the second script. every minute or what not.
the second script checks for the database value set by script 1 to decide whether to run entirely or not.
I would suggest doing the timer in Javascript rather than PHP.
Put a timestamp in the user's $_SESSION to indicate when they started the event, and then have Javascript call back to the browser after five minutes.
PHP would still need to know the start time (to prevent the user from hacking the game by tweaking the Javascript time-out), but it wouldn't need to actually do any count-down timing or sleeping or anything like that itself.
You could fork the process and in the child fork, do a sleep for 5 minutes before executing your second script. I've tested this and it appears the child process will still execute even after the parent has finished. Something like
//initial code
$pid = pcntl_fork(); //fork the process
if ($pid==0) // if in the child
{
exec("sleep 300; php second_process.php"); //sleep for 5 minutes and execute second script
return; // or exit
}
// rest of initial script...
The "return;" is important as the rest of the script will execute a 2nd time (i.e. in the child) unless it's there.
Someone asked about the purpose of this and your answer was:
"I'm making a browser-based game and I want it to if someone wants to build a building it takes * minutes and then finishes"
You don't actually need to time an execution for this. You can do it all in one run by storing buildStartedAt and buildFinishedAt as part of the building-schema.
Now maybe you want the building to have a nice animation when it finishes, then you just do all of that on the frontend but make sure nothing meaningful can be done with the building if the timestamp is before the buildFinishedAt time in order to a void cheating by potential hackers.
Are you looking for that?
sleep php.net

To use sleep() or cron job

I have this mail script I have to run a few times.
To start the script I will use cron, but the script has to run 2 or 3 more times (with an hour apart).
What's the best way to do this?
To use the sleep command for an hour, or at the end of the script, place some code, so that the script will create a new cron job to run it self after an hour?
Thanks
Unless there's some cost savings in keeping the script running in memory, you're better off using cron to invoke it every hour, as needed.
0 0-2 * * * /usr/local/bin/mail-script.php
You can choose multiple hours using the - syntax, or the comma syntax:
0 0,1,2,3 * * * /usr/local/bin/mail-script.php
If it needs to maintain some form of state, use a temporary file to keep saved state.
Do:
> man 5 crontab
To see if your *nix handles the above cases.
Finally, unless you know the script has to run only 2-3 times, you're better off putting the logic about whether to "run or not to run" in the PHP script itself, and then just run it every hour.
One advantage of using sleep() is that it could be more portable. For example, on many systems I work with, users are not allowed to have their own cron jobs - so writing your program to take care of its own timer-ness might be an advantage.
An alternative to sleep() might be using SIGALRM (so your script catches an interrupt and executes code at a certain interval - when that interrupt is thrown.)
I mean, I'd recommend using cron - but here are some alternatives!
I'm not sure either approach (sleeping for an hour, or creating cron jobs from php) is ideal, how about a cron job that runs every hour anyway, then your php script checks whether it should run?
Why not just set the cron criteria so it fires those specific times? Cron is pretty flexible in that aspect.
Update your question with when you want it to fire off and I can give an example.

Categories