1

What I've to do it's a bit complicated.

I've a python script and I want to run it from PHP, but in background. I had seen somewhere that for run a python script in background I have to use the PHP command exec(script.py) to run without wait for a return: and thus far no problem.

First question:

I have to stop this loop script with another PHP command, how to do this?

Second question:

I have to implement a server-side timer, who stops the script at the end of the time.

I found this code:

<?php
$timer = 60*5; // seconds
$timestamp_file = 'end_timestamp.txt';
if(!file_exists($timestamp_file))
{
  file_put_contents($timestamp_file, time()+$timer);
}
$end_timestamp = file_get_contents($timestamp_file);
$current_timestamp = time();
$difference = $end_timestamp - $current_timestamp;

if($difference <= 0)
{
  echo 'time is up, BOOOOOOM';
  // execute your function here
  // reset timer by writing new timestamp into file
  file_put_contents($timestamp_file, time()+$timer);
}
else
{
  echo $difference.'s left...';
}
?>

From this answer.

Then, there is a way to implement it in a MySQL database? (The integration with the script stop is not a problem)

Community
  • 1
  • 1
Northumber
  • 315
  • 2
  • 3
  • 15
  • https://secure.php.net/manual/en/function.exec.php#89716 Use that to get the process ID, store it in a file or database, then just kill the process that has that ID later on. Keep in mind, however small, the process could've been stopped already and another process ended up using that ID instead (which would mean you're killing a different process) – xorinzor Dec 31 '16 at 15:30

1 Answers1

1

That's actually pretty simple. You can use a memory object caching system. I would recommend memcached. Memory objects from memcached can be accessed literally from anywhere in your system. The only requirement is that a connection to the memcached backend server is supported. (PHP does, Python does, etc.)

Answer to your first question:

Create a variable called stopme with the value 0 in the memcached database.

Connect from your python script to the memcached database and read the variable stopme permanently. Let's say the python script is running when the variable stopme has the value 0.

In order to stop your script from PHP, make a connection from your PHP script to the memcached server and set stopme to 1.

The python script receives the updated value instantly and exits.

Answer to your second question:

It could be done like explained in my answer before through reading shared variables, but additionally I would like to mention that you also could use a cronjob to kill a running script.

Community
  • 1
  • 1
user3606329
  • 2,405
  • 1
  • 16
  • 28