How to make mysql run Delet query automatically - mysql

I Have an OTP table and I want to delete data that is older than 5 minutes automatically
Then how could I make trigger or procedure for that?

You must use according Event Scheduler procedure.
CREATE EVENT remove_old_rows
ON SCHEDULE
EVERY 10 SECOND
COMMENT 'Delete the rows that are older than 5 minutes from OTP table.'
DO
DELETE
FROM OTP_database.OTP_table
WHERE created_at < CURRENT_TIMESTAMP - INTERVAL 5 MINUTE;
Do not forget to enable Event Scheduler.

Don't do it! Just create view to get the most recent data:
create view v_otp as
select otp.*
from otp
where otp.created_at >= now() - interval 5 minute;
Anyone who uses the view only sees the most recent data.
Then you can leisurely delete old data during a period when the database is not busy.
An added benefit is that this is always accurate. If an event or job gets delayed, then your users might see old data. Further, this does not involve complicated locking and transaction semantics when the server is busy.

Related

MySQL Event Scheduler run daily in a specific time frame

I wrote a query in MySQL which I want to run daily on our wordpress server. Using Cronjobs gave me a lot of collate errors, so I took the easier rout with the Event Scheduler which is easier to implement via phpMyAdmin.
Now I would like to run the query only at specific times: Once per hour, between 8 am and 5 pm.
Is this possible using Event Scheduler? I know of:
STARTS = ...
ENDS = ...
But as far as I know, that only sets global values (start and end once). Is there any possibility to set a recurring daily end? Or do I have to use cron for that?
Issue
The problem from what I see is that you want to do two things:
Run something once per hour (interval)
But not continue doing this action outside of a specific daily timeframe.
The first part is very easily to take care of using the example from:
MySQL Event Scheduler on a specific time everyday
The second part is the one that creates the complexity.
Solutions
You have two available solutions that I can think of:
Schedule an event with interval 1 hour, and add a check in your SQL statement / function / procedure to check that that time of day is within the specific time interval you want.
Schedule multiple events (9-10) for the specific times e.g. (8:59am, 9:59am...4:59am)
Personally I would prefer solution one since it is much easier to change a value in your script than have to reschedule / manage 9-10 events.
Quick Example
delimiter |
CREATE EVENT hours
ON SCHEDULE
EVERY 1 HOUR
STARTS (TIMESTAMP(CURRENT_DATE))
DO
proc_label:BEGIN
IF curtime() >= "08:00" OR curtime() <= "17:00" THEN
LEAVE proc_label;
END IF;
select 1+1;
END |
delimiter ;
Just a little sugestion, to change from OR to AND.
IF curtime() >= "08:00" AND curtime() <= "17:00" THEN
LEAVE proc_label;

deleting item from database after 30 minutes [duplicate]

This question already has an answer here:
Delete MySQL Row after 30 minutes using Cron Jobs/Event Scheduler
(1 answer)
Closed 9 years ago.
I want to have a script, that counts how many users are online on my site, but this script should count guests, so I have created a database for session, this script gives user an ID and set 30 minutes session, and now I have a problem, because if he is not active more than 30 minutes, he should be deleted from the database, because I want to count by ID how many users are online, and I have headache how can I do this.
Is there a simple way to do this?
As stated by Barmar in their answer here:
DELETE FROM my_table
WHERE timestamp < NOW() - INTERVAL 30 MINUTE
Write a PHP script that executes this SQL, and add a crontab entry
that runs it every 30 minutes. Or use the MySQL Event Scheduler to run
it periodically; it is described here.
Since you have not mentioned any database in specific, I give you a general idea of how to implement it:
You can have a table like this:
USER_SESSIONS
(
USER_ID //UNIQUE_ID
LAST_ACTIVE //TIMESTAMP
)
Here is the functionality you can associate to implement the session:
When a user logs in, you create an entry in this table.
When a user logs out, you delete the corresponding entry from this table.
When user does some activity (depends on how you want to track activity in the front end), update the corresponding TIMESTAMP of the user.
Create a DB Schedule (a continuously running process) that monitors the TIMESTAMP column. All good databases have a built in scheduler. Here is some pseudo code for the scheduler:
FOR each entry in USER_SESSIONS
If (CURRENT_TIMESTAMP - LAST_ACTIVE) > [30 mins] then
delete the entry of the corresponding user from this table.
//This will essentially cause a session timeout.
End If
LOOP;
I hope you got a fair idea of how to implement it.

Triggers performance based on system timings

My question might sound stupid but i would be glad if someone answers to this:)
when we set a trigger which performs an action like now(), curdate(), curtime() on dependency of systems date and time, does it consider the change in time that happens before the deletion or update,
example - i have a trigger set today(6-11-2012) at 5 pm i have to delete a set of rows tomorrow i.e on 7-11-2012 at 5 pm. in this time gap i change the timings or date of my system, now does the trigger consider the newly changed date and time for deleting the rows.

MySQL Triggers, deleting a row after inactivity?

I've done some googling but can't really get much relevant information. I'm trying to set a date/time for certain rows to be deleted depending on activity. If active, the time would be bumped to a later time unless activated once again.. Otherwise it will be deleted. I've managed to sort the rows when activated (inserted/updated) in activity.
Thanks in advance.
Firstly do not put this update/delete in a trigger if you have millions of rows that needs to be deleted you are going to see a huge performance hit on inserts/updates. It is not the best place for it. You can create either a cron job as Filype suggested. Or if you want to keep it all in MySQL use the MySQL Event scheduler.
Go to this page to read more about scheduling events in MySQL:
http://dev.mysql.com/doc/refman/5.1/en/events.html
MySQL Event allows you to schedule things on MySQL on a regular basis.
The code would look something like
CREATE EVENT myevent
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 HOUR
DO
DELETE FROM MyTable Where Expired< NOW();
Here is a suggestion, I haven't tried yet, you might think to update the row with deleted=1 instead of actually deleting the record.
CREATE TRIGGER deleteInactiveRecords AFTER UPDATE,INSERT ON myTable
FOR EACH ROW BEGIN
DELETE FROM myTable WHERE updated < (updated-((60)*60*24))
END;

Way to automate deletion of expired records in MySQL?

I've googled around and searched the MYSQL docs ad nauseam and couldn't find a succinct way of automating deletion of records that exceeded a given timeframe. I've been able to get a query in 5.1 to cast a value of TIMESTAMP to DATETIME within a DIFF function with the current time to see if it meets the criteria of expiration. I've read that 5.1 now has the capability of running scheduled tasks but not much in the way of configuring it. I'm not using triggers for this.
In the MySQL docs for 5.1, it refers to creating an event:
'CREATE
[DEFINER = { user | CURRENT_USER }]
EVENT
[IF NOT EXISTS]
event_name
ON SCHEDULE schedule
[ON COMPLETION [NOT] PRESERVE]
[ENABLE | DISABLE | DISABLE ON SLAVE]
[COMMENT 'comment']
DO sql_statement;
schedule:
AT timestamp [+ INTERVAL interval] ...
| EVERY interval
[STARTS timestamp [+ INTERVAL interval] ...]
[ENDS timestamp [+ INTERVAL interval] ...]
interval:
I currently use Toad (which has been a Godsend). My query affectively removes any records that are more than 30 minutes old. I just need to find how this event gets invoked...
Thanks!
You are talking about using the MySQL Scheduler. Once you create that event, MySQL will call it automatically at whatever interval you configure it with. If you are having trouble getting it set up, post the query and error your are getting.
Write a query and have it ran on a job every so often. Say, check for the expired rows every 30 minutes or so.
If it doesn't have to be exact, and you're just housekeeping, you can tie the process to another one. If you can afford the time.
If you have an old invoice file, purge it when month-end is run (possibly a lot of records, but it's a batch process anyway). Purge old inventory items when you add new ones (less frequent, but fewer records possibly). Keeping an access log table? Purge it when the most recent record in it falls on a different day than today. (for low traffic logfiles) And so on.