Can I use asynchronous timer in PHP and how to do it?

I have an application with PHP (on websites) and I need to create several timers lasting three seconds. When the time in the timers increases, I change the bool variable. Each timer changes its own variable. I cannot use sleep because my program must be active.

I thought the timer in the php reaction would be asynchronous, but it behaves the same as sleep (). Here is my code:

    $loop = \React\EventLoop\Factory::create();
    $timer = $loop->addTimer(3, function() {
        // some acts
    });

    $loop->run();

How to make an asynchronous timer?

+4
source share
3 answers

You can use background workers. Gearman is great for these things.

+1
source

, Gearman, , Gearman - gearman. http://gearman.org/protocol/. - Beanstalkd.

http://kr.imtqy.com/beanstalkd/

PHP, php .

beanstalk pheanstalk. https://github.com/pda/pheanstalk, .

:

$pheanstalk = new Pheanstalk('127.0.0.1');

$delay = 3; // delay in seconds
$pheanstalk
  ->useTube('choose_tube_name')
  ->put("job payload goes here\n",
      PheanstalkInterface::DEFAULT_PRIORITY, // 1024 as standard
      $delay,
      PheanstalkInterface::DEFAULT_TTR // I think that after 60 seconds by default, if not deleted by consumer after reserving job, it is automatically released back onto the queue to be consumed by another consumer.
);

while (1) {
    $job = $pheanstalk
      ->watch('choose_tube_name')
      ->ignore('default')
      ->reserve();

    echo $job->getData();
    $pheanstalk->delete($job);
}

, / choose_tube_name ​​3 . 3 , .

, , , , , , while, , .

. , , , . / . while / while, .

+1

Since I use windows and Gearman is poorly installed on it, I found another solution in the form of pthreads. I just create a new thread and put a dream (3).

0
source

Source: https://habr.com/ru/post/1672564/


All Articles