How to run a PHP function after specific time on server? - php

I have a function which adds a new blog post to my database.
After running add_new_post() function the post should be approved by my another function approve_post().
But I don't want to approve post immediately. I want to run approve_post() function in time between 1 to 5 minute (random).
Now I am using this code:
function add_new_post() {
*my code of adding post*
$time = rand(60, 300);
echo $time;
sleep($time);
approve_post();
}
But browser shows loading until sleep ends. Also, I found that my Windows machine shows time execution error.
Is there a way to run approve_post() function in the background without showing page loading to the browser?
I would be grateful for а code example.

First, you need to increase the maximum execution time of a PHP script by using the following link https://www.plus2net.com/php_tutorial/max-ex.php
Then use sleep() function to delay code execution as:
<?php
echo date('H:i:s');
sleep(15);
flush();
echo "<br>";
echo date('H:i:s');
?>
Reference link
Or you can CronJob

There are multiple options.
You can use ajax which is required to open a page or you can use a Cron job. I will prefer to use Cron job
The concept will same, for an example. The post table must has created_date ,approve_date and approve_status. So when you create the post it will save the approve_date too.
Example, You create a post on 18:00 then the approve_time will 18:05. Then the background process (ajax or Cron job) will check the approve_status first then execute the approve process when live time same like approve_time
ref : cron job & Ajax
sorry for my English

Related

laravel 6 cannot set delay code for job queue

i need help for correct delay code for run the job.. im using laravel 6 and now i doing scraping youtube number of view.
let say that i have table that fill with youtube link. when i do scraping to youtube. we need to add delay time before we go to other link. if we dont make delay it. youtube will block our access. i want to add delay maybe 30 second for each loop.
so what i already trid in my app/Console/Commands/GetYoutube.php file is this
use App\Models\Youtube;
use App\Jobs\GetYoutubeView;
use Carbon\Carbon;
...
public function handle()
{
$youtubes = Youtube::get();
foreach ($youtubes as $youtube) {
GetYoutubeView::dispatch($youtube->link)->delay(Carbon::now()->addSeconds(30));
}
}
i tried this code. but still can't add delay 30 seconds for each loop
other think that i add delay code sleep(30); on jobs file. here is what i've done in my jobs app/Jobs/GetYoutubeLink.php
public function handle()
{
sleep(30);
// Scraping youtube total number of views code
}
but this same. it not delay 30 second for each loop. what is the correct delay code for this.
please help. what is correct delay code in my case.
When you call dispatch the job is dispatched. You are calling the delay after that. You should create the job and delay the job before dispatching.
$youtubes = Youtube::get();
$start = Carbon::now();
foreach ($youtubes as $youtube) {
$job = new GetYoutubeView($youtube->link);
$job->delay($start->addSeconds(30));
dispatch($job);
}
EDIT
You where calling multiple now dates before, you should only create one date, and keep adding 30 seconds to it.

How to Execute a PHP task and put on hold/sleep another task that is being executed right after until the first one is completed/half through?

I have a PHP Code that does some tasks.
Lets say someone executes the code by doing so https://localhost/code.php.
I have an employee that executes the script over curl from a separate server, what is the best way to prevent him from launching the script twice, before the (already running) script is actually completed/finished goes to the end.
TLDR: I would need a function, to wait until the task/code (that's running now) completes and the secondary task that is trying to be launched has given (sleep for few seconds or until the first tasks completes).
TLDR2: Looking for function [The title says it]
Any ideas? thanks.
While a session won't work with cURL, the idea is valid -- you need to set something persistent outside of your script. So, how about writing to a local file, or writing to a database?
if ( file_exists('lock.txt') ) die;
file_put_contents ('lock.txt', 'This file prevents script execution', LOCK_EX);
(... your script code here...)
unlink ('lock.txt');
If you know that there is only one user who will hit your server you can simply use session data.
<?php
session_start();
if (true === $_SESSION["NOT_FINISHED"] ?? false) {
die("Previous job is not finished yet!");
} else {
$_SESSION["NOT_FINISHED"] = true;
// start whatever job need to be done here
...
// when job is done and finished lets release out busy flag
unset( $_SESSION["NOT_FINISHED"]);
}

Making Crons to quit running an existing script

I am running a script which constantly works over my Database. How ever It is necessary to restart the script once an hour. Obviously I can't do that automatically. I don't want to use daemon, its too complex for me right now. Easier solution is to use cron job but biggest drawback is, it won't stop the last script. Script runs in infinite while(true) loop
However is that possible if I make function in a script, lets say
function exitScript()
{
exit;
}
And then on Cron job if i do something like
php /home/Path/public_html/webservice/myScript.php exitScript and then
php /home/Path/public_html/webservice/myScript.php
What will be the format and How can I run both one by one using cron job or make another PHP who does so?
I need advice.
Here is a little trick easy to made which you can use..
1st set you cron jobs to run on each hour.
* */1 ..... cronjob.php
2nd At start of your script define 1 constant with time:
define('SCRIPT_START_TIME', time());
3rd At your exit script set up a condition check to exit if 59 minutes are passed from this constant to current time.. :)
function exitScript()
{
if((time() - SCRIPT_START_TIME) > 59*60){
exit();
}
}
4th at each while LOOP start the exit script .

PHP sleep delay

In PHP, I want to put a number of second delay on each iteration of the loop.
for ($i=0; $i <= 10; $i++) {
$file_exists=file_exists($location.$filename);
if($file_exists) {
break;
}
//sleep for 3 seconds
}
How can I do this?
Use PHP sleep() function. http://php.net/manual/en/function.sleep.php
This stops execution of next loop for the given number of seconds. So something like this
for ($i=0; $i <= 10; $i++) {
$file_exists=file_exists($location.$filename);
if($file_exists) {
break;
}
sleep(3); // this should halt for 3 seconds for every loop
}
I see what you are doing... your delaying a script to constantly check for a file on the filesystem (one that is being uploaded or being written by another script I assume). This is a BAD way to do it.
Your script will run slowly. Choking the server if several users are running that script.
Your server may timeout for some users.
HDD access is a costly resource.
There are better ways to do this.
You could use Ajax. And use a timeout to call your PHP script every few seconds. This will avoid the slow script loading. And also you can keep doing it constantly (the current for loop will only run for 33 seconds and then stop).
You can use a database. In some cases database access is faster than HDD access. Especially with views and caching. The script creating the file/uploading the file can set a flag in a table (i.e. file_exists) and then you can have a script that checks that field in your database.
You can use sleep(3) which sleeps the thread for 3 seconds.
Correction sleep method in php are in seconds.
Hare are two ways to sleep php script for some period of time. When you have your code and want to pause script working for some time use these functions.
In these examples the first part of code will be done on script run and the second part of code will be done but with time delay.
Using sleep() function you can define sleep time in seconds.
Example:
echo "Message 1";
// The first part of code.
$timeInSeconds = 3;
sleep($timeInSeconds);
// The second part of code.
echo "Message 2";
This way it is possible to sleep php script for 3 seconds. Using this function you can sleep script for whole number (integer) of seconds.
Using usleep() function you can define sleep time in microseconds. This sleep time is convenient for intervals that require more precise time than one second.
Example:
echo "Message 1";
// The first part of code.
$timeInMicroSeconds = 2487147;
usleep($timeInMicroSeconds);
// The second part of code.
echo "Message 2";
You can use this function if you want to sleep php for smaller time values than second (float). In this example I have put script to sleep for 2.487147 seconds.
Have you considered using a PHP Daemon script using supervisorD. I use it in multiple tasks that are required to be running all the time.
The catch is making sure that each time you are running your script you check for memory resources. If its too high, stop the process and then let it restart itself up again.
I have successfully used this process to be always checking database records for tasks to process.
It might be overkill but worth considering.

How to run a php function after certain time without using cron

I have a block of code and want to run it after certain time intervals, say after every 3 seconds. If I get required result it should die otherwise another request will be sent after 3 seconds. Any idea to do it with php.
Thanks in advance for any help
You can sleep in a loop:
while (true) {
$result = doSomething;
if (resultIsGood) {
break;
}
sleep(3);
}
If you don't want to keep the browser waiting, you can look up ignore_user_abort() solutions on Google.
If what you want to execute MySQL queries (and nothing else), maybe using the MySQL event scheduler could fit your need:
http://dev.mysql.md/doc/refman/5.5/en/events-overview.html

Categories