PHP DIY series: 2. Delay task

Time:2021-7-20

Delay task is different from timing task. Timing task usually has fixed cycle and definite trigger time. The delay task usually has no fixed start time. It is often triggered by one event, and another event is triggered within a period of time after this event.

We might as well set up an actual scenario. If the e-commerce system fails to pay successfully within 15 minutes after placing an order, the system will automatically cancel the order.

Let’s implement the code first, and then explain in detail:

//We define an abstract and two methods, startafter and startat

Redismanager is an encapsulated redis class implemented in singleton mode. We also post the code, and then explain the above code.

<? php

Ordered set

redis 127.0.0.1:6379> ZADD saif 1 redis
(integer) 1
redis 127.0.0.1:6379> ZADD saif 2 mongodb
(integer) 1
redis 127.0.0.1:6379> ZADD saif 4 mysql
(integer) 0
redis 127.0.0.1:6379> ZRANGE saif 0 10 WITHSCORES

1) "redis"
2) "1"
3) "mongodb"
4) "2"
5) "mysql"
6) "4"

If you have redis visualization tool, you will find that the structure of ordered collection storage is as follows:

row value score
1 redis 1
2 mongodb 2
3 mysql 4

Let’s look at the code again. We use the timestamp as the score and the object as the value to store them in the redis ordered set.

file_ put_ Contents (string $file name, mixed $data [, int $flags = 0 [, resource $context]]): int – writes a string to a file

implement

Let's try to write the task first

Execution code:

class DelayTaskTask

We can set a timing task to execute the above code every minute.

After we execute, we will find that once the time we set has passed, text.txt will be written continuously.

Code more miscellaneous, I have a demo code, you can see.

Delaytask delay task based on redis

In this way, we use the redis ordered set to complete a very basic delay task.

problem

  • If the run method code takes too long to execute, what’s the problem with executing once a minute?
  • It is executed every minute, with a long interval. Can it be optimized?

php

This work adoptsCC agreementReprint must indicate the author and the link of this article

Before the collection, you may as well order a like to try!!!

Recommended Today

Front end 123: how browser caching works

Workflow for browser caching Obtaining content through the network is slow and expensive. Large responses require multiple round-trip communications between the client and the server, which will delay the time for the browser to obtain and process content, and increase the traffic cost of visitors. Therefore, the ability to cache and reuse previously acquired resources […]