Execute script when date matches mysql cell - mysql

I have a debian machine with a mysql server.
On mysql I have a table that contains a number of rows with a datetime field.
How can I execute a php script when the date and time of the machine match with those specified in any mysql record?
a) Mysql triggers ?
b) Deamon that runs in background and checks time every n seconds ?
c) Cron?
Let me know!

Polling the MySQL will work but surely is not efficient, especially when there are a lot of "triggers".
So use a cronjob. Note: MySQL-Queries cannot schedule or cancel cronjobs. So the (i guess) PHP-Script updating that date field also has to schedule the cronjobs. Also, every time the column changes you will have to cancel the previously scheduled cronjob and schedule a new one.

Since you can't run shell command from within Mysql database the MySql Triggers are no good. The MySQL Scheduler is therefore useless too. So you need an external script to help.
I'd suggest to create a (php) script and add it to the crontab to run every minute. Its task would be to check for matching dates in the database and run whatever command you need.

I think that the easiest solution is to use , if possible , the at command.
Basically after inserting the data into mysql do the following:
1)Create (using PHP) a BASH script that runs the php file
script_1.sh should look like this:
!#/bin/bash
php /path/to/file.php
and make it executable with :
exec("chmod +x script_1.sh");
2)create a second BASH script that executes the first at the desired time:
script_2.sh should look like this:
!#/bin/bash
at H:M Y:M:D < script_1.sh
Make script_2 executable and run it with the exec command.

Related

How can I track the execution of `source filename` command in mysql

How can I track the execution of source filename command in mysql so that I can have the filename and path of sql scripts that's been run. Google didn't help or may be I didn't use the right keyword.
So when I execute source ./test/file.sql (without errors preferably)
I want an entry in "source_history" table with current_time,filename(along with path) which I can do if I could figure how to track.
It'd be of great help if anyone could help me in keeping track of the command source.(Something like a trigger event for insert or update on table)
(may be, tracking all command in that sense and then while exiting mysql, get the query history and check for source)
Hope that makes sense.
Thanks in advance.
The problem is that the source command is not a MySQL command, it is a command in MySQL's command line interface, which is also named MySQL.
CLI only passes the sql commands within the file to the MySQL server, therefore the server cannot be aware of the exact file used for executing the command.
MySQL own documentation the source command (see the link above) suggests the most obvious solution:
Sometimes you may want your script to display progress information to
the user. For this you can insert statements like this:
SELECT '<info_to_display>' AS ' ';
So, the simples way is to create a table with fields for path, event type (start / stop) and a timestamp and add insert statements to the start and end of each sql file that log the start and the end of each batch and supply the name of the file hard coded in the insert statements. You may want to create a script that adds these commands to the sql files.
Alternative is to create a batch file that receives a path to an .sql file in a parameter, invokes MySQL's CLI, logs the start of the batch process in mysql, launches the .sql file, and then logs the completion of the batch in MySQL.

How to keep track of last successful run in bash

I am running an ETL script that loads data from mysql into teradata. The script aims to select all rows later than the timestamp of the last successful run of the bash script. Since I do not have write access to the mysql database, I need to store the last run timestamp with the bash script. Is there an easy way to store the timestamp of a successful run? I was thinking I could have a file that I would touch at the end of the script and then check its mtime, or just parse out the timestamp from a log file. What are some better strategies to do this?
Within your script, use set -e1 so that the script exits immediately if any command within the script fails. Then, at the end, log successful completion with a unix timestamp date +%s.
You can then use SELECT FROM_UNIXTIME(<YOUR TIMESTAMP>, <YOUR MYSQL DATE FORMAT>)2 to pull rows that are newer than the last successful completion.
One big caveat: I would not rely solely on timestamps to approach this problem. I would pull from MySQL with some time overlap and check primary keys for each insert into teradata to avoid inserting duplicates. To follow this approach, just subtract 1800 from <YOUR TIMESTAMP> to ensure a 30 minute overlap.

How to delete expired data with cron job

I want to auto delete my data on mysql database which has expired date with cron job every 5 minutes.
For example I have a table (TableName) with one of column (ExpDate) as "2015-04-10 21:30:00", it's timestamp format type and UTC time zone.
I have tried creat a cron job command like this:
*/5 * * * * delete * from TableName where ExpDate > NOW();
But it didn't work, I've searched around in SO and elsewhere but have not found a direct answer to this. So, I created this question and hope someone can help me. I am a beginner in cron job, I would be very grateful if you could help me.
Cron doesn't know about SQL commands. Cron knows about running executable commands. This leads us to the answer - you need to either directly call the MySQL command line client in the crontab (probably a bad idea), or you need to write a script that does what you want, and then get cron to execute it.
A sample script would be:
USERNAME=[username]
PASSWORD=[password]
DATABASE=[database]
MYSQL=/usr/bin/mysql
$MYSQL -u $USERNAME -p$PASSWORD $DATABASE -e "DELETE from ....."
You would put this script somewhere safe, because it contains your password. Let's say you called it purge_expired.sh, you would need to make it executable like this chmod +x purge_expired.sh, and then tell cron to execute that script instead of trying to make it run the SQL commands itself.
Somehow I missed the memo where MySQL got its own event scheduler, you might want to use that instead.
An example specific to you would be something like:
CREATE EVENT DeleteExpired
ON SCHEDULE EVERY 5 MINUTE
DO
DELETE FROM TableName WHERE ExpDate < NOW();
You also need to make sure the event_scheduler variable is set to on in order for this to run.

How can I automate a SQL query via PHPMyadmin?

Because of a buggy wordpress plugin I am using, I have to manually run the following query many times during a single day:
update table_name set column_name="";
It simply drops the contents of the given column name.
So how can I make my server do it automatically every 30 minutes for instance, through PHPMyadmin?
I am not a PHP nor a SQL SAVVY. So please take that into consideration :)
I am on Hostmonster.com , and they have MySQL client version: 5.1.60 and phpMyAdmin v. 3.4.9
If are using UNIX and like you can put the following into your crontab:
30 * * * * "/<path_to_mysql>/mysql -u <username> -p<password> -e "update table set column=\"\""
This will do every 30 minutes what you need to do.
For Windows you can create a Batch file that does the same and execute it using Windows Scheduler
While it is a bit of work to do this every N minutes, it is quite easy to do it statistically every N requests. Put
<?php
define('MYPLUGIN_CLEANUP_PROBABILITY',5);
function myplugin_cleanup_db($postid) {
global $wpdb;
if (rand(0,99)<MYPLUGIN_CLEANUP_PROBABILITY))
$wpdb->query('update table_name set column_name=""');
}
add_action('shutdown', 'myplugin_cleanup_db');
?>
into a .php file and put it into your plugins directory after adapting your cleanup probability. Then activate this plugin and off you go.
To my knowledge, PHPMyAdmin can not automate it directly.
You have a few options:
Create a cron job to run the SQL statement (too advanced?)
Utilize WP Cron to schedule an event to run the SQL statement through WordPress. (possibly easier)
Fix the plugin (my vote, but could be difficult)

linux 'at' command like functionality for mysql database

I need to update a particular field in the database based on some timestamps in the same table. Now are there time based triggers which can be scripted to look at the value and do things? much like the linux 'at' command.
I know one way is to execute a script using the at command. I am asking about something at the database level itself.
MySQL has an event scheduler.
See
http://dev.mysql.com/doc/refman/5.5/en/events.html