Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
896 views
in Technique[技术] by (71.8m points)

telegram bot - To send a message with a delay in PHP (without "sleep" function)

Trying to make a dice-roll function in my telegram bot. How it works right now:

  • When a user sends "roll" bot replies with sendDice method and sends another message with result like "you rolled 5, you won and blah-blah .." > how it looks <

The problem is — the second message should not appear instantly, ideally after dice-roll animation is finished. My first and obvious try on that was to add "sleep(3)" before sending the second message, and it worked fine, until I realized it completely delays the execution of my script for those 3 seconds. (if two users rolled at the same time, one of the users has to wait until another guy's roll will be finished). So it's not cool

What can I use? :c

question from:https://stackoverflow.com/questions/65830857/to-send-a-message-with-a-delay-in-php-without-sleep-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The easiest option is to add the "task" to the "queue". The queue can be a table in the database with timestamps and chat id, when and to whom to send a message. Start another process, for example, which is started by cron, and it works for one minute. During that minute, he goes to the database and checks to see if there is something that needs to be sent now.

Crontab config

Open crontab

sudo crontab -e

Add next string

* * * * * php /path/to/cron.php >> /path/to/log/file/for/debug.log 2>&1

Cron run your script every 1 minute.

Cron.php "live" 60 second cron.php:

    $now = time();
    $expectedTime = $now + 60;
    while (true) {
        Worker::run();
        if ($expectedTime < time()) {
            die(0);
        }
    }

Where Worker::run() your method, which get records from db, check timestamp and send message


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...