php: I want a code to be executed every 1 minute - php

I will try be clear and specific :)
So i have a website, where people purchase stuff from each other.
To keep everything organised, when someone buys something from another user, That purchase will be moved to a table in database, called Pending. (Note: The purchased is not processed yet)
(so all purchases will be moved and queued into this 'Pending' table)
Now what I want to do is, that this table 'Pending', starts processing 1 purchase at a time automatically (let's say 1 purchase every one minute --> if there are any ofcourse).
Now I have no idea how to do this, if someone can atleast give me a hint on what can I use or what to look for, in order to do this.
Note: am using php & mysql
Thanks in advance :D :)

You can write a PHP script to be executed by a cron job. PHP doesn't have to be executed from a browser request, it can be run form the command-line. Cron would make use of this functionality.
The crontab line to execute a command every minute would be as follows:
* * * * * /path/to/script.php
Each column has a * indicating "any value", so this indicates to run the script "any minute, any hour, any day, any month, any day of week"

A cronjob is going to be your best bet, http://en.wikipedia.org/wiki/Cron

Make some file named MovePending.php with a MySQL query that 'moves' the purchases from Pending to Processed, and run it every minute via a cron job.

Related

Run laravel jobs one time at specific time only

I came across a situation i want to trigger some code at specific time, i.e when user does booking, the freelancer must accept/reject the booking request, if he doesnt, after x duration (15* mins lets say) it would be rejected and user would get push notification. All code is done but currently im running a cronjob after each 1 minute which checks for any unresponded bookings and checks when their time (15mins, dynamic) passed so then I execute my code for afterward, it is not good i guess as its running db queuries over and over each minute.
I'm aware with laravel queue jobs as well but didnt see anything for me to run that job for a specific time only (i.e execute this job after 15mins, if it isnt responded, reject it)
have you looked at Queue delay?
https://laravel.com/docs/9.x/queues#delayed-dispatching
This sounds like what you are looking for, I would just trigger the queue and delay when they make a booking so it executes 15 minutes after.
Use scheduled tasks.
use App\Console\Commands\SendEmailsCommand;
$schedule->command('emails:send Taylor --force')->daily();
$schedule->command(SendEmailsCommand::class, ['Taylor', '--force'])->daily();
https://laravel.com/docs/9.x/scheduling#scheduling-artisan-commands

Run php calculations when the browser is closed

I'm trying to create a YouTube-like service where the content creator is paid for their content however I'm a bit stuck.
The website needs to calculate the amount of views a content creator gets a month to calculate how much they need to be paid and then through PayPal API pay them by the end of the month. The problem is that this needs to be done even when the page is closed. I assume this is done on a server but I not sure if that's the case or even how to do it.
Thanks
Just googling real quick on cron, I found this website: https://www.pantz.org/software/cron/croninfo.html
I have used cron a lot before and the information here seems adequate to answer your question; it at least will arm you with the knowledge needed to do what is required.
An example for a cron job could be the following:
50 * * * * /myTask.php
What this says is "run this script 'myTask.php' every 50 minutes, every hour, every day of the month, every month, every day of the week" - simply put, run every 50 minutes.
The aforementioned task can be added to the crontabs file by using the following command from the terminal crontab -e
I found the solution. It turns out that the service hosting my website has an option to run cron jobs internally so I can make a script to loop through all the users, calculate their view earnings and pay them and run it at the beginning or each month.

PHP scripts in cron jobs are double processing

I have 5 cron jobs running a PHP file. The PHP file checks the MySQL database for items that require processing. Since cron launches the scripts all at the same time, it seems that some of the items are processed twice, or even sometimes up to five times.
Upon SELECting the file in one of the scripts, it immediately sends an UPDATE query so that other jobs shouldn't run it again. But looks like it's still double processing.
What can I do to prevent the other scripts from processing an item that was previously selected by the other cron jobs?
This issue is called "race condition". In this case it happens due to SELECT and UPDATE, though called one after another, are not a single operation. Therefore, there is a chance that two jobs do SELECT the same job, then first does UPDATE, and then second does UPDATE. And so they proceed to run this job simultaneously.
There is a workaround, however.
You could add a field to your table containing ID of current cron job worker (if you run it all on one machine, it may be PID). In worker you do UPDATE first, trying to reserve a job for it:
UPDATE jobs
SET worker = $PID, status = 'processing'
WHERE worker IS NULL AND status = 'awaiting' LIMIT 1
Then you verify you successfully reserved a job for this worker:
SELECT * FROM jobs WHERE worker = $PID
If it did not return you a row, it means other worker was first to reserve it. You can try again from step 1 to aquire another job. If it did return a row, you do all your processing, and then final UPDATE in the end:
UPDATE jobs
SET status = 'done', worker = NULL
WHERE id = $JOB_ID
I think you have a typical problem to use semaphores. Take a look at this article:
http://www.re-cycledair.com/php-dark-arts-semaphores
The idea would be at first of each script, ask for the same semaphore and wait until it be free. Then SELECT and UPDATE the DB as you do it, free the semaphore and start the process. This is the only way you can be sure that no more than one script is reading the DB while another one is about to write on it.
I would start again. This train of thought:
it takes time to process one item. about 30 seconds. if i have five cron jobs, five items are processed in 30 seconds
This is just plain wrong and you should not write your code with this in mind.
By that logic why not make 100 cron jobs and do 100 per 30 seconds? Answer, because your server is not RoadRunner and it will fall over and fail.
You should
Rethink your problem, this is the most important as it will help with 1 and 2.
Optimise your code so that it does not take 30 seconds.
Segment your code so that each job is only doing one task at a time which will make it quicker and also ensure that you do not get this 'double processing' effect.
EDIT
Even with the new knowledge of this being on a third party server my logic still stands, do not start multiple calls that you are not in control of, in fact this is now even more important.
If you do not know what they are doing with the calls then you cannot be sure they are in the right order, when or if they are processed. So just make one call to ensure you do not get double processing.
A technical solution would be for them to improve the processing time or for you to cache the responses - but that may not be relevant to your situation.

Update mysql table every twenty four hours automatically

I was wondering how I could set up a script (I'm assuming it would be a cron job) that would reset a field in a mysql table every twenty four hours back to zero. I would want it to reset the field for every user not just a specific person. I know nothing about cron jobs unfortunately, but maybe I don't even need to use them. I am very unsure on how to solve this issue. Thanks for the help!
What about using the MySql event scheduler itself?
http://dev.mysql.com/doc/refman/5.6/en/events-overview.html
create a python script that connects to the mysql table and performs the update query.
Create a cron job that runs 1 time every day that executes:
python updateValue.py
It is quite easy, and the best way I can think of doing it.
The crontab argument would look like:
0 0 * * * python updateValue.py

How to delete mysql row after time passes?

I have no idea where to start with this one:
I have a database that stores postID and Date.
What I want to do is have my website auto delete all rows where Date is less than today. This script can't have any user input at all. No button clicks, nothing. The script must run every day at midnight.
I've been looking all over the place for something that does this and I've found absolutely nothing.
You can use PHP script and use cron job on your cpanel.
Example:
cronjobcommand.php
<?php
include 'your_db_connection';
mysql_query("DELETE FROM your_table_name WHERE Date < NOW()");
?>
I have attached a screenshot below for your more reference.
For those out there who are on a shared hosting, like 1and1's, and can't use cron, here are 2 alternatives :
mysql events enable you to place a time trigger on mysql, which will execute when you'll want, without having to be fired by any kind of user input
if you cannot create mysql events because you're on 1and1 :(, an alternative is to use webcron
You just need to tell webcron the url of the php script you'd like to be run, and they'll trigger it for you at the intervals you want
Why using cronjobs everyday?? Why not filter data on output. For example in your select check if post date equals today with adding a simple where:
SELECT * FROM `posts`
WHERE (DATE(`post_date`) = DATE(NOW()));
This way you're not required to do your database managements/cronjobs on any special time and it will be used just for database managements. Afterwards you can delete unnecessary data at any time using by mysql command like:
DELETE FROM `posts` WHERE (
DATE(`post_date`) < DATE(NOW())
)
Most hosts provide a cron(8) service that can execute commands at specific times. You use the crontab(1) program to manage the crontab(5) file the describes when to run which commands.
There's a lot of functionality available to you, but if you write a program (shell script, php script, C program, whatever) that runs the appropriate MySQL commands, you can call the program via cron(8) in an entirely hands-off fashion.
Run crontab -e to edit your current crontab(5) file. If none exists, hopefully you'll get one with a helpful header. If not, copy this:
# m h dom mon dow command
The columns indicate the minute, hour, day of month, month, and day of week to execute commands. All the numbers in the columns are essentially ANDed together to decide when to run commands.
Thus, midnight every night would look like this:
0 0 * * * /path/to/executable
It's remarkably flexible, so put some time into the documentation, and you'll find many uses for it.
You should set cron job (scheduled tack.) for it.
A cron job is an automated program setup for Linux and Unix operating systems. It allows the user to execute several commands or functions at a specific time and date.
you have cron Job in your cpanel setup. first you need to make a php script with your logic for delete record after each date. take date from server and write script for delete.
then go to cron tab in your cpanel and do settings for time interval to run cron and give path of your php script file.
MySQL doesn't have a task scheduler. So you have to use the task scheduler of your Operating System (CRON under Linux), or to lunch a basic task checker sub-script during the script of the main page (on another page that is supposed to display the changing data).

Categories