简体   繁体   中英

Mysql PHP Cron for updating user stats

I'm trying to build a php cron job that will run every 24 hours and updated user statics in a mysql database. The problem I've run into is I'm not sure how I should insure that the same users values are not updated in a loop meaning none of the others are updated. I was trying to do it with a while loop however it hasn't gone well.

So basically it should work like this
1. cron starts ->
2. updates each users stats in mysql database ->
3. cron ends

MySQL solution:

You require MySQL event to run on a time basis.

And I suggest you write the update statements based on your condition and link the same procedure to the event scheduler you want to run on every day start.

You can do it as following:.

Example :

delimiter //
drop event if exists event_scheduling_sample;

create event if not exists event_scheduling_sample
--  on schedule every 86400 second starts 00:00:00
--  at timestamp( adddate( current_date, 1 ),'00:00:00' )
--  on schedule every 1 day 
    --   starts current_timestamp 
    --   ends current_timestamp + interval '5' day
--  on schedule every 1 day 
    --   starts current_timestamp 
    --   ends timestamp( current_date,'23:59:59' )

  on schedule every 1 day 
     starts timestamp( current_date + 1, '00:00:00' )

  comment 'event scheduling sample'
  do
    call db_name.procedure_name_that_updates_the_user_records();
;
//
delimiter ;

Refer to : MySQL: CREATE EVENT Syntax

Default state of Event Scheduler is DISABLED.
You require to enable it by any of the following statements.

SET GLOBAL event_scheduler = ON;
SET @@global.event_scheduler = ON;
SET GLOBAL event_scheduler = 1;
SET @@global.event_scheduler = 1;

When the Event Scheduler is ON, the event scheduler thread is listed in the output of SHOW PROCESSLIST as a daemon process, and its state is represented as shown here:

mysql> SHOW PROCESSLIST\G
*************************** 1. row ***************************
     Id: 1
   User: root
   Host: localhost
     db: NULL
Command: Query
   Time: 0
  State: NULL
   Info: show processlist
*************************** 2. row ***************************
     Id: 2
   User: event_scheduler
   Host: localhost
     db: NULL
Command: Daemon
   Time: 3
  State: Waiting for next activation
   Info: NULL
2 rows in set (0.00 sec)

Once the Event Scheduler is set ON, you would see it working.

Refer to : MySQL Event Scheduler Configuration

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM