I am using Laravel's artisan scheduler to manage cron jobs for an application. One of the features of this app are virtual shops that "restock" at an interval that's logged in the database (i.e stock_min = 5 and stock_max = 15 would mean the shop would restock every 5-15 minutes). These values can change at any time.
How would I go about setting up the cron in Laravel so it would adhere to the interval given with a sufficient amount of randomness and look to see if the interval has changed since the last restock?
You'd need to create a model called 'stock_update_tracking' or something similar, to log when the next time the stock should be restocked.
stock_update_tracking
next_update
Then, you can call a cron job every minute and simply do a check to see if the next_update value is more than the current timestamp.
$schedule->call(function() {
$nextUpdate = DB::table('stock_update_tracking')
->select('next_update')
->where('next_update', '<' Carbon::now())
->count();
if($nextUpdate) {
// Update the stock
// Calculate a new next update time
$newNextUpdate = Carbon::now();
$newNextUpdate = $newNextUpdate->addMinutes(rand(5,15));
// Save the newNextUpdate value in the stock_update_tracking table
DB::table('stock_update_tracking')->update(['next_update' => $newNextUpdate])
}
})->everyMinute()->withoutOverlapping()
Related
So here is what I am trying to accomplish:
User selects how often they want their post to be moved to the top of the page, whether it be every 30 minutes or every hour or every 2 hours, etc. They will be able to select how many times that it will do this. So if they select it to update every hour for 5 hours, it will then update the date/time in the database to the current time and then updates that time every hour for the next 5 hours and cancels it after the 5 hours are up.
I was thinking of running a PHP script like this to update the table since the ads are displayed by date DESC:
<?php
//cronjob.php
$id = $_SESSION['ad_id'];
$date = date('Y-m-d H:i:s');
$query = "UPDATE ads SET ad_date = :date WHERE ad_id = :id";
?>
Is there a best way to do that or will a CRON job that is selected by the user going to be too much load on the server to have users setting up CRON jobs continuously.
I saw this one approach and wonder if it is possible to set it up for this purpose. I am still getting familiar with CRON jobs.
How to start/stop a cronjob using PHP?
I will be setting this up on Godaddy's server:
Godaddy Cron jobs
Appreciate the help.
One method is to store the required updates in a new database table, containing fields such as the post id, how many times to update, interval, how many updates are left, the time at which the first update should take place ( or the time for next update ) .
Then, create a php script that fetches data from this table and take necessary action for each post. Check if it's time to update the post, if yes then update, else don't ( check time with accuracy upto minutes, don't check seconds. If you can, do this time checking with SQL and not in php to reduce the data being fetched ). It's better to perform all updates in a single query to maximise efficiency.
Then set up a cron job on the server that runs this php script every minute or whatever minimum time interval you need.
This way, you can get away with just one cron job😉
If you need even more efficiency, then at the end of this script, check if there are any more updates pending, if none then delete the cron job. Then, set up your code such that whenever a user creates a new update, check if the cron job exists, if it doesn't then create it ( this additional dynamic cron job is only for efficiency freaks. If there are frequent update requests, it might be better to avoid creating/deleting cron jobs )
What I have:
I have an existing cron job file that runs daily every 15 minutes (e.g. 1.10pm, 1.25pm, 1.40pm, 1.55pm), to check in the database for emails to be sent. I am using PHP and mySQL.
My issue:
Due to a limit by the hosting, I have to use the same cron job file for another task - check the database at every end of the month.
My question 1:
I only want the check to be done once on that day - would my following solution work? If I don't want to update the database that I have done the check already, I will have to set the task to only be done if the time now is equal to 8.55am (a timing that the cron job would run at). So if the cron job runs at 8.55am, it would do
$TimeNow = new DateTime();
$TimeNow = $TimeNow->format('H:i');
$TimeToRun = new DateTime('8:55');
$TimeToRun = $TimeToRun->format('H:i');
if ($TimeNow == $TimeToRun) {check database}
My question 2: Would the following work to check if it is the end of the month? What can I do to check if this works because it is not the end of the month now?
if(gmdate('t') == gmdate('d')){}
I want a functionality that insert data every month...
I have some idea to implement this that is as follow....
When User Create 'INVOICE' at that time the 'INVOICE' automatically generated every next month once user create it.
Let have some code...
INSERT INTO INVOICE (id,user,date,bill_money) VALUES ('','XYZ','25/03/2015','100');
this one works very well now every next month same entry should be automatically inserted..
For that i have logic that when user log-in into portal at that time first i have retrieve user's last log-in and from that date to currently log-in date i try to insert those data which are 30 days old data...
I select next day(date) after user's last log-in date and then Check for every that up to current day(date).
To retrieve user last log-in date
echo $this->session->userdata('name')
To check interval lastlogindate() + INTERVAL 30 DAY == NOW()
If this becomes true then then insert data
But here problem is that i want to implement for month, quater, year
Is this flow is better or there can be another way to do this..??
I heard about cron job and MySQL Event which one is best in this two and how they are working which one is effective performance wise...
I want suggestion on this. Thank you....
If you want a recurring invoice. Just store the invoice once and schedule a cron job that will run daily at scheduled time. Cron job will run your php script to do whatever you want to do like : store invoice in db or email it to user. If you don't know about cron jobs, basics can be found in this answer : How to create cron job using PHP?
EDIT : you will have to schedule cron job using cli
Mysql events
I think this is better for me i haven't use Cron Job...
for Mysql event checkout syntax and have a fun...
I'm trying to create a computer reservation system, where user chooses a computer and select the time how long he will be using this PC. In that time other persons can't reserve this pc, I need to find a solution, how to automaticaly delete all rows containing reserved pc's after their time expires. Thank you for the advice.
The common way to handle this is to store an expires_at timestamp on the reservation row. Then your query to find any "open" reservations would have WHERE 'expires_at' < NOW() or something similar.
This is an untested answer, that may only be a suggestion, but I just started looking at these, so am interested in feedback as well. i'm still working through possibilities and drawbacks, but it might well suit your need.
Take a look at MySQL Events, an article about it is here, and official syntax at Mysql Docs.
Per the article:
An event is similar to a trigger. However, rather than running in
response to a data change, events can be scheduled to run any number
of times during a specific period. In effect, it’s a database-only
cron job.
Pondering this, I'd envision a procedure that deleted anything >1hr (if that's the expiration). This procedure would be TRIGGERED on new inserts to get rid of anything expired at that moment, but also in an event to run every 15 minutes or so so that automatic deletes by the trigger aren't dependant on somebody else adding a reservation to trigger that procedure.
If your server is linux, you can use cron jobs to check once a day every reservation dates. If these dates have expired .. modified field reserves to be available.
Normally I would do it this way:
when storing a reservation, store date_from and date_to both of datatype DATETIME
when checking if there is a computer free check for all computers and filter with WHERE '{$my_date}' >= date_to AND '{$my_date}' <= date_from - by this You should be able to get all the PCs that are not reserved within a certain time...
To be complete in the solution, you need to run a CRON job which calls a query to remove all reservations that have a reservation_time + (15 * 60) < unix_timestamp().
I am assuming you have a time that the reservation was placed or started and are using UNIX/Epoch Timestamps.
Instead of doing a expires_now, if you know it will always be a fixed interval ie 15 minutes, you can do:
DELETE FROM reservations WHERE reservation_time + (15 * 60) < unix_timestamp()
Something you could look into is managing cron job's from PHP, http://www.highonphp.com/cron-job-manager.
The above script will, when a reservation is created, insert an entry into /etc/cron.d/ and you could configure it to run at the expected reservation endtime. Then inside the php file which would be executed, you could do:
DELETE FROM reservations WHERE id = :id
In my web app, user is given 5 min to do some job, and after that 5 min, the job should be passed to other person. So, each job would have user_id and that user_id value has to be changed every 5 min. The thing is that there are multiple jobs, and we want to use 15sec interval for script to be periodically run to take care of this change. And job will passed to other person maximum of 4~5 times, and it will be disregarded after that.
The job & user data is stored in MySQL database.
My initial thought was to use cron-job with PHP script file that let the cron-job runs PHP script every 15 sec. PHP file will read the job table, select all the jobs which have time value past 5 min ago, and fetch them to other users (doesn't matter if one user get the all jobs or not). I just want to periodically run it without taking too much resources.. but is it a good idea? Wouldn't that take too much resources once the number of jobs increases?
While it does not have to be consistence (13~16 sec interval is just fine) we want that script does not stop.
Create a cronjob that reads the table status updated time.
-- show table status like table;
example: update_time: 2011-04-10 15:27:32
than you can do the logic in the cronjob to check that date. and if that date is greater than 15 seconds ago or whatever, than you have an updated records.