2012年01月的日志

用PHP设定WINDOWS计划任务

通常在LINUX下可以用CRON来完成这项任务,那么在WINDOWS平台可以使用系统自带的任务计划来完成。

WINDOWS的任务计划有一个可视化的管理器,具体位置是“控制面板”  - ”任务计划“ (WIN7则是在”控制面板“ – ”管理工具“中)。可视化的管理器使用非常简单,网上也有大堆的教程介绍,我就不细说了。

这里稍微提一下在命令行下的操作,以及如何使用PHP来对其进行操作。

任务计划在命行下的名字为schtasks,其实也就是windows/system32下的一个程序。

创建任务 schtasks /Create /TR taskname /TR taskrun /st starttime /sd startdate

更多的参数和解释可以参照 schtasks /Create /?

修改任务 schtasks /Change /TR taskname …

更多的参数和解释可以参照 schtasks /Change/?

另外还有查询、删除、终止等功能,就不一一列了,运行schtasks /? 会有很详细的帮助,而且都是中文的(当然用英文系统的童鞋就不是了 :P

用PHP操作命令行其实非常简单,只需要用到exec函数,那么我们只需要把创建(或改,删)的命令使用exec来执行就OK了。

说到这里,先不要急,事情还没完。当你试图用exec去执行schtasks的时候,发现啥都不会返回,同时也没有按照你的意愿成功的执行任何东西。

我也为这个问题稍稍苦恼了一下,但很快在PHP  documentation的评论里找到了答案:

via http://www.php.net/manual/en/ref.exec.php#74897

Scheduling WinXP tasks with schtasks.exe and using PHP to execute the command, may sometime fail to work.

This is because, Apache does not have the privilege to access some of the System Files when placing the scheduling. The way I’d do: is by creating a normal user account and assign Apache service to logon as that account.

Open the ‘services.msc’ in the ‘Run’ window, look for Apache in the listing, right click and get to ‘Properties’. Click at the second tab ‘Log On’ and fill in the ‘This account’ fields.

Of course, Apache needs to be installed as Service during its first setup.

Hope this helps anyone.

Fendy Ahmad

看到这里我想大部分人已经明了了。是因为Apache权限不够的问题,只需要在services.msc里面找到apache服务,然后赋予有对应权限的用户即可。