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.
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:
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
Let's try to write the task first
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.
In this way, we use the redis ordered set to complete a very basic delay task.
- 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?
This work adoptsCC agreementReprint must indicate the author and the link of this article