How to execute PHP code in Linux every 500 milliseconds?

I have an http server on Linux.
I have some PHP code that stores variables into the cache using memcache and I would like to execute this code every 500 milliseconds whenever the server is running, even after a server restart.
I was thinking of implementing a service but I don't have much experience with Linux so I don't know how to do this or if it is even the right approach.
I also heard of cron-jobs but I see that they run by the minutes and not by the seconds.
How can I execute PHP code in Linux every 500 milliseconds(Code would be helpful)?

4

2 Answers

You could use a simple shell-script for that:

#!/bin/bash
while true; do php /path/to/your/script.php & sleep 0.5s;
done

The '&' will fork the process in the background, so the timing should be somehow accurate. I guess after some time it will become out of sync with a real clock, so you might either want to add timestamps to whatever your script does or use an approach with an daemon which uses the system time.

(Thanks for the input in the comments)

I recommend adding that script with systemctl. This tutorial looks fine for that:Creating my own systemd service files

3

Since you are familiar with PHP you can make a PHP daemon/service. I have made a PHP service for myself once because I had to use a library that was available only in PHP. It runs without any issue for many years now.

Here are some information about PHP daemons:

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like