Polling a running php cli script
I want to run a php script from the command line that is always running and constantly updating a variable.
I then want any php script that is run in the meantime (probably but not necessarily from the web) to be able to read that variable at any time.
Anyone know how I c开发者_如何学运维an do this?
Thanks.
Here, you want some kind of inter-process communication mecanism.
You cannot use a PHP variable for that : these are local to the script they're in.
Which means you'll have to use some "external" tool to store your data, like, to only speak of a few :
- a file
- a database (SQLite, MySQL, ...)
- some shared-memory segment
In each case, you'll have :
- One script that write to the data-storage space -- i.e. your first always running script
- One or many other scripts that will read from the data-store
You should write the variable to a file with the CLI script and read from that with the other script.
Be sure to use flock
to prevent race conditions.
You can write a php socket based server script, which will listen on desired port. Find article here. Then your client php script can connect to it either locally or from the web and retrieve any data, including variables. You can use any simple protocol designed by you or well known like XML to transfer variables.
Lots of idea's:
- At set intervals it appends/writes to a file.
- You use sqlite and write your data to it.
- Your use a small memcached service as your intermediary.
- You go somewhat crazy and write a socket class, listen on a set port, then make non-blocking calls to check.
1-2 are probably the simplest 3 would work great if you need to query the value a lot 4 would be fun, but might not be worth the effort.
精彩评论