How to create a trigger that resets values to zero after 30 days? - mysql

I have a table 'users'. In that table there is a field balance whose datatype is ENUM('Yes','No'). Now I want to create a trigger that is fired when the balance is set to "Yes". Also I want to reset the value of Balance to NO after 30 days.
I am using PHP Codeigniter. And I have a reseller table who has its own users. So Each reseller has some users.
So when a reseller sets the balance of user to yes the trigger should
be fired and after 30 days should set user balance to NO
Also the balance of each user should be Reset uniquely. I mean one uses's balance is set to yes today and user-two balance is set to Yes tomorrow . So how will trigger know when to fire for that each specific user?

My solution is
Maintain a column like updatedon.
Write a stored procedure to set balance to NO when updatedon is 30 days and balance is YES(according to your critaria)
Run a Job daily to invoke the stored procedure(It will set only 30 days back updated records)

In order to track date you need to keep a column on which user updated_to_yes_date. When ever user update that enum column to "Yes" you should set current date to updated_to_yes_date.
Now lets code the controller for cron job.
class Cronjob extends CI_Controller {
function index() {
// Get Date before 30 days.
$today = new DateTime();
$dateBefore30days = $today->modify('-30 days');
$this->db->update('users',array('enumcolumn'=>'No'), array('enumcolumn'=>'Yes', 'updated_to_yes_date'=>date_format($dateBefore30days , 'Y-m-d'));
}
}
I have not tested above controller but it will help you.
Now its time to set up cron job. You need to run this cron job every day. To know how to setup cron job on cPanel CLICK HERE
Now we need to execute controller method from command line. For that go to codeignitor Running via the CLI document.
In our case it will be like
$ php index.php cronjob index
In many case we need to provide full path to index.php like
$ php /path/to/webroot/index.php cronjob index

Related

how to Update status of order in mysql after 30days using sequelize nodejs

I have problems is: Auto-update order status if that status doesn't have any update in 30 days.
For example, the current status is " processing" and during 30days later, no more update on this. So the MySQL auto-update order status to "on Hold
I found and guest it something related to Hook, but I don't know how to implement it
depends on how you run you app. I'll suggest using e.g. some cron to get such instances and update it's status.(e.g. https://www.npmjs.com/package/node-cron)
Set it for example to run once a day, query such instances depends on build in column updatedAt. Or just to add some other column which will be updated with current date, depends what rules you want to apply
you can use cronjob.as npm says Cron is a tool that allows you to execute something on a schedule.
for install cron - 'npm i cron'
the (*) shows in order given details.
Seconds: 0-59 Minutes: 0-59 Hours: 0-23 Day of Month: 1-31 Months:
0-11 (Jan-Dec) Day of Week: 0-6 (Sun-Sat)
how to initialize cronjob:
var CronJob = require('cron').CronJob;
var job = new CronJob(
'* * * */30 * *',
function() {
console.log('every 30 days it is auto updated!');
},
null,
true,
'America/Los_Angeles'
);
make sure other parameters pass according to your application
and also cron use different port then your application.
As suggested by Damian you need to use a kind of CRON job which runs everyday to check for expired orders(created more than 30 days ago without any update).
You can use Bull with PM2
Create a processor in Bull and a queue and use the CRON functionality of Bull to set this job to run everyday usually at 12:05 AM or any time you see suitable.
The job would fetch all orders which have status "processing" and were created more than 30 days ago and update them.
Use PM2 to run Bull

How to trigger event in NodeJs based on database time values?

I need to perform some actions in my app based on user's input. For e.g. if user selects 17:00-18:00, the timeframe is updated in the MySQL db and something should happen in that specific time.
Could someone tell me how can I achieve that?
You can use cron jobs for it.
For example, if you need to do some actions based on time value in your DB, you can write some code, that gets the current date and selects from MySQL all raws if your current date is between the date range of that raw and process them.
Then just make some cronjob that calls your code every minute, or an hour or whatever you need.
You can use cron package for that.
Here is an example:
const { CronJob } = require('cron');
// example cron job
const yourFunction = require('./yourFile.js');
// setting cron for example cronJob
const cron = new CronJob('0 * * * * *', yourFunction, null, true);
cron.start();
Or you can use Linux's crontab, you can read about how to use it here.
Configure frequency of cron with cron scheduler, you can play with it here.

Create a mysql event with condition

I currently have a mysql database where I keep data about rented books. When somebody rents a book, I save on the database an expiration date.
So, I want to create an mysql event to update the book status when it is not returned in time. How can I create this event?
Here's what I'm trying:
CREATE EVENT `EXPIRAR` ON SCHEDULE EVERY 1
HOUR STARTS '2016-07-16 00:00:00.000000' ENDS '2018-07-29
00:00:00.000000' ON COMPLETION NOT PRESERVE ENABLE DO DO IF
mtl_aluguel.dataLimite=CURRENT_DATE THEN
UPDATE mtl_aluguel SET mtl_aluguel.estado='Expirou'
END IF
But I'm getting Syntax errors on the IF.
mtl_aluguel is the name of my table.
Like #Drew said, my event doesnt make any sense. So I updated it:
CREATE EVENT `EXPIRAR` ON SCHEDULE EVERY 1
HOUR STARTS '2016-07-16 00:00:00.000000' ENDS '2018-07-29
00:00:00.000000' ON COMPLETION NOT PRESERVE ENABLE DO UPDATE mtl_aluguel SET mtl_aluguel.estado='Expirou' WHERE mtl_aluguel.dataLimite = CURDATE() AND mtl_aluguel.estado!= 'Expirou'

Check for a date/time conflict MySQL

OK... So I have a calendar, in a custom PHP application built using CodeIgniter, which pulls its entries from a MySQL database. In the table containing the entry data, there are 3 fields that govern the date (start_date), time (start_time) and duration (duration) of the entry. Now, as the end-user moves an entry to a new date and/or time, the system needs to check against these 3 fields for any schedule conflicts.
Following are some vars used in the query:
$request_entry_id // the id of the entry being moved
$request_start_date // the requested new date
$request_start_time // the requested new time
$request_duration // the duration of the entry being moved (will remain the same)
$end_time = ($request_start_time + $request_duration); // the new end time of the entry being moved
My query used to check for a schedule conflict is:
SELECT t.id
FROM TABLE t
WHERE t.start_date = '$request_start_date'
AND (j.start_time BETWEEN '$request_start_time' AND '$end_time'))
AND t.id <> $request_entry_id
The above query will check for any entry that starts on the same date and time as the request. However, I also want to check to make sure that the new request does not fall within the duration of an existing entry, in the most efficient way (there's the trick). Any suggestions? Thanks in advance!
It's easier to figure out the logic if you first think about the condition for when there is no conflict:
The new event ends before the existing one starts, or starts after the existing event ends.
For there to be a conflict we take the negative of the above:
The new event ends after the existing one starts, and starts before the existing event ends.
In SQL:
SELECT t.id
FROM TABLE t
WHERE t.start_date = '$request_start_date'
AND ('$end_time' > t.start_time AND '$request_start_time' < addtime(t.start_time, t.duration))
AND t.id <> $request_entry_id

Working hours only trigger

I would like to run this script (embed drive list in a site) that I have used but only set the trigger to run it during office hours Monday - Friday.
I would like the script to run every 5 minutes but stop over night and at weekend. So I figured that I need to:
Have a script that programatically creates a trigger to run the actual function during the day and give that a trigger to run once at the beginning of each day.
Have a second script to delete the days trigger run once at the end of the day.
I am doing this as I have just learned that there is a maximum amount of CPU time you can use during a day so I do not want to waste it during times I don't need the list updated.
I can see how to create a trigger but it is not clear how to create a trigger to activate another script (function).
I think it would be quite easier to insert a small routine at the beginning of your main function that checks the time of the day and simply 'returns' when out of office hours.
This way you can let your trigger set to 5 minutes all the time.
This 'hour check' will be very short in terms of processing time.
here is a test function to show how it works :
function officeHours() {
var nowH=new Date().getHours();
var nowD=new Date().getDay();
// Logger.log('day : '+nowD+' Hours : '+nowH)
if (nowH>17||nowH<8||nowD==6||nowD==0) { return }
Browser.msgBox('time to work !');//normally your real function should begin here...
}