如何构建php可触发服务


How to build php triggerable service

我使用examplep-php apache服务器

我不能

  1. 退出后继续php
  2. 退出前向客户端发送响应
  3. 将http请求与资源共享同步

我想要

  1. 将php作为服务运行,php可以在不连接到客户端的情况下运行
  2. php执行可以由客户端使用http请求触发
  3. php(连续或触发)可以完全访问资源
  4. php可以在响应时将数据从资源发送到客户端

有什么方法可以做这些事情吗?或者我应该试着看看其他服务器,或者套接字编程是唯一的方法吗?

这……有点复杂。

我想要

run php as service where php may run without being connected to client
php execution can be triggered using http request by client
php (continuous or triggered) have full access to the resources
php can send the data from the resources to the client on response

第一件事很容易实现。只需将PHP作为命令行安装,并在无限循环中运行(命令行没有过期时间),或者,可能更适合您的需要,作为crontab服务。有几种实用程序可以实现这一点;他们要么每X秒运行一次脚本,要么在脚本终止后立即重新启动。

如果脚本以某种方式(例如通过数据库)检查它是否有"工作要做",那么您的目标2也就实现了:HTTP web客户端脚本只需要在数据库中插入详细信息,就好像主运行脚本已经由web服务器启动一样。实际发生的情况是,主脚本通常会立即终止(可能会休眠几秒钟,以免服务器过载),但下次运行时,它会找到要做的工作并执行

您的目标3可以通过以更多权限运行主脚本来实现。用户脚本不能"访问所有资源",但可以谦虚地请求数据,而主脚本(更安全)可以优雅地允许读取这些数据,并将其写入客户端可能获得数据的数据库(或文件系统)

最后,您的目标4可以通过读取数据并将其提供给客户端脚本的客户端浏览器来实现。

示例工作流程:

- 15:55:00 The master script runs. SELECT worktodo FROM thingstodo returns nothing
- 15:56:00 The master script runs. SELECT worktodo FROM thingstodo returns nothing
- 15:56:17 The client runs; it is a request for data from serial port.
- 15:56:17 The request is stored in the DB and gets ID 12345 and status "WAITING"

假设一-15:56:18客户端在写入"Work has been queued,please wait"(工作已排队,请稍候)后终止,并向自身发送一个HTTP头循环:

    Location: http://mylocation/script.php?check=12345

假设二-15:56:19客户等待,比如说十秒钟,以防万一,每秒运行一次检查,看看工作是否完成。如果是,则按照15:17:35进行;其他人就像假设一一样,说"我会回来的",然后带着Location头死去。-15:56:20由于Location标头,客户端脚本被重新加载,check=12345。它与DB连接,看到12345的状态未完成,显示"正在工作…"动画,等待五秒钟,然后再次显示Location:。

- 15:57:00 The master script gets awakened and finds there is one job in WAITING status; updates it in LOCKED status and places its own IP and PID in the proper fields, then decodes the work details, sees what needs to be done and does it.
- 15:57:33 The work is done and the row gets updated again; now STATUS=COMPLETED
- 15:57:35 Meanwhile the client gets called again, but this time it finds COMPLETED, so happily fetches the data and shows it to the customer, also deleting the row not to clutter the DB.

其他可能性:-主脚本找到作业行中填写的电子邮件字段,向用户发送一封带有适当链接的电子邮件。-主脚本实际上大部分时间都处于休眠状态,绑定到端口XYZ上的套接字,而客户端脚本在需要执行某些操作时"唤醒"它。这减少了请求和应答之间的延迟。

将php作为服务运行,php可以在不连接到客户端的情况下运行

您可以使用cron任务运行PHP脚本