Reputation: 57
My code follows MVC structure, or more specifically I am using Codeigniter. I want to run something in the background (infinite loop). But I want to stop it at some point. How to do it?
I have tried passing a stop signal to the running action but not working
class My_controller extends CI_Controller
{
public $stop = false;
public function start()
{
ignore_user_abort();
set_time_limit(0);
do{
....//do something, such as trading bitcoins
}while(! $this->stop);
}
public function stop()
{
$this->stop = true;
}
}
So what I want to do is first start the running by typing "mydomain.com/my_controller/start" on the browser, and then stop it by typing "mydomain.com/my_controller/stop" on the browser. But the stop action does not return, and it just keeps waiting. Could anyone tell me how to stop the background running action? I cannot stop it simply by killing PID because I am using shared web hosting.
The reason why I am doing this is because I want to write code for automatic bitcoin trading, i.e., my application will keep running 7 X 24 in the background, getting market information, analyzing the data and sending commands for trading to platforms. So I need to control the stopping when necessary.
Upvotes: 2
Views: 411
Reputation: 2841
If you're familiar with running CLI commands and your shared hosting provider allows you to have shell access to your account, you could write a handler to run via a CLI command. CodeIgniter makes this cleverly simple. Once you've got it working, you can type the CLI command followed by an ampersand (eg, php -f index.php controller_name route_name &
and the process will run in the process until killed with the kill
command.
Beware, however, that an infinite loop can quickly cause out-of-control CPU and/or RAM usage on your system, and your shared hosting provider won't be very happy with you if they detect that. I suggest you use sleep() to pause for the maximally acceptable amount of time between executions of the loop of your code. Also, go over your code carefully and make sure you're not increasing memory usage on each loop of your code by doing something like endlessly appending to an array or something like that.
Upvotes: 1