How to write delay queue (timer) in PHP

background

PHP does not have a timer. It relies on system tools such as crontab, and there is no delay method such as defer in go. This article introduces several postures for writing delay queues in PHP.

Definition of delay queue

The ordinary queue is first in, first out, but the delayed queue is not, but the weight of time is added. It is hoped that it will be executed first when it arrives.

In a sense, the structure of the delay queue is not like a queue, but more like an ordered heap structure weighted by time.

Hash

Use a unique identifier for the key to ensure that each task is not repeated and easy to delete, and then add the name of the function to be called, the timestamp, and the parameters to the value.
Iterate every second, then take out the time to execute, and then delete.

入队:hSet key:uuid value:{timestamp,function,param}
出队:timestamp > now do function(param)

The problem is obvious, it needs to be traversed, hGetAll is a taboo spell.

ZSet

As mentioned earlier, in fact, the delay queue is an ordered heap structure, that is, a time weight needs to be added. Then, isn't an ordered set like this?

Join the team: ZADD KEY timestamp task, we add the tasks that need to be processed and delay the processing time according to their needs as Score into ZSet.
Dequeue: ZRANGEBYSCORE KEY -inf +inf limit 0 1 WITHSCORES. In this way, the tasks that need to be performed can be retrieved. Delete after execution: Zremrangebyscore KEY -inf +inf limit

Time wheel

In fact, there is a small problem with the above algorithms. Tasks on the same timeline are sequential. For example, they are all executed at 00 in the morning. How come who comes first? Because tasks have priority or order, of course, you can also set multiple keys according to priority. There are many ideas.

Here is an algorithm that is also used by many message queuing software, the time round algorithm.

In fact, it is very simple, that is, put a queue at each time point, and then use a task to scan the time wheel, just like a clock, so that the corresponding task can be executed at the point.

The picture comes from the Internet

For example, if the task is scanned to 2, you need to add a task with a delay of 3 seconds, and then directly add it to 5.

Of course, for the different time granularity, we must set multiple time wheels, just like the hour hand, minute hand and second hand.

What are the benefits of this?

  • The first two methods, in the final analysis, need to traverse + sort, and the time wheel, only need to gradually scan and gradually take out tasks. The efficiency is much higher, the more tasks the more obvious.

Guess you like

Origin blog.csdn.net/happy_teemo/article/details/115334610