php脚本的Cron作业,需要非常长的执行时间 [英] Cron job for php script that requires VERY long execution time

查看:102
本文介绍了php脚本的Cron作业,需要非常长的执行时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个php脚本作为cron作业运行,执行一组简单的任务,为数据库中的每个用户循环,大约需要30分钟完成。这个过程每小时开始,需要尽可能快速和高效。问题Im有,像任何服务器脚本,执行时间不同,我需要找出最好的cron时间设置。

I have a php script run as a cron job that executes a set of simple tasks that loops for each user in the database and takes about 30 mins to complete. This process starts over every hour and needs to be as fast and efficient as possible. The problem Im having, is like with any server script, execution time varies and I need to figure out the best cron time settings.

如果我每分钟运行cron,需要在分钟结束前20秒停止脚本的最后一个循环,以确保当前循环在时间结束。

If I run cron every minute, I need to stop the last loop of the script 20 seconds before the end of the minute to make sure that the current loop finishes in time. Over the course of the hour this adds up to a lot of wasted time.

我想知道如果它的一个坏主意,简单地删除php执行时间限制和运行脚本

Im wondering if its a bad idea to simple remove the php execution time limit and run the script once an hour and let it run to completion.... is this a bad idea?

推荐答案

假设你想要一个工作尽快,不要使用cron。 Cron适用于需要在特定时间发生的事情。它经常被滥用来模拟一个后台进程,理想的情况下,一旦工作出现处理工作。你应该编写一个持续运行的守护进程。 (注意:你也可以看一个消息/工作队列类型的系统,有很好的库也可以这样做)

Assuming you'd like the work done ASAP, don't use cron. Cron is good for things that need to happen at specific times. It's often abused to simulate a background process that would ideally process work as soon as work appears. You should probably write a daemon that runs continuously. (Note: you could also look at a message/work-queue type system, there are nice libraries out there to do this too)

你可以从头开始写一个守护进程使用 pcntl函数(因为您不关心多个工作进程,它 super-easy 来获得一个在后台运行的进程),或者欺骗,只是制作一个脚本永远运行并通过屏幕运行,或者使用一些实用的库代码,例如PEAR的系统:Daemon nanoserv

You can write a daemon from scratch using the pcntl functions (since you don't care about multiple worker processes, it's super-easy to get a process running in the background.), or cheat and just make a script that runs forever and run it via screen, or leverage some solid library code like PEAR's System:Daemon or nanoserv

一旦守护进程的东西被照顾,你真正关心的是有一个循环,永远运行。你需要注意你的脚本不会泄漏内存,或者消耗太多的资源。

Once the daemonization stuff is taken care of, all you really care about is having a loop that runs forever. You'll want to take care that your script doesn't leak memory, or consume too many resources.

一般来说,您可以执行以下操作:

Generally, you can do something like:

<?PHP
// some setup code 
while(true){
    $todo = figureOutIfIHaveWorkToDo();
    foreach($todo as $something){
        //do stuff with $something
        //remember to clean up resources so you don't leak memory!
        usleep(/*some integer*/);
    }
    usleep(/* some other integer */); 
}

它会工作得很好。

这篇关于php脚本的Cron作业,需要非常长的执行时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆