开发者

Polling a running php cli script

开发者 https://www.devze.com 2022-12-26 14:33 出处:网络
I want to run a php script from the command line that is always running and constantly updating a variable.

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:

  1. At set intervals it appends/writes to a file.
  2. You use sqlite and write your data to it.
  3. Your use a small memcached service as your intermediary.
  4. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消