开发者

Possible to optimize Php script to limit impact on server memory and cpu?

开发者 https://www.devze.com 2023-04-01 13:41 出处:网络
I have a PHP-script running on my server via a cronjob. The job runs every minute. In the php script i have a loop that executes, then waits one sevond and loops again. Essentially creating a script t

I have a PHP-script running on my server via a cronjob. The job runs every minute. In the php script i have a loop that executes, then waits one sevond and loops again. Essentially creating a script to run once every second.

Now I'm wondering, if i make the cronjob run only once per hour and have the script still loop 开发者_如何学Cfor an entire hour or possible an entire day.. Would this have any impact on the servers cpu and or memory and if so, will it be positive or negative?


I spot a design flaw.

You can always have a PHP script permanently running in a loop performing whatever functionality you require, without dependency upon a webserver or clients.

You are obviously checking something with this script, any incites into what? There may be better solutions for you. For example if it is a database consider SQL triggers.


In my opinion it would have a negative impact. since the scripts keeps using resources. cron is called on a time based scale that is already running on the server. But cronjob can only run once a minute at most.

Another thing is if the script times out, fails, crashes for whatever reason you end up with not running the script for at max one hour. Would have a positive impact on server load but not what you're looking for i guess? :)

maybe run it every 2 or even 5 minutes to spare server load?

OR maybe change the script so it does not wait but just executes once and calling it from cron job. should have a positive impact on server load.


I think you should change script logic if it is possible.

If tasks your script executes are not periodic but are triggered by some events, the you can use some Message Queue (like Gearman).

Otherwise your solution is OK. Memory leaks can occurs, but in new PHP versions (5.3.x) Garbage Collector is pretty good. Some extensions can lead to memory leaks. Or your application design can lead to hungry memory usage (like Doctrine ORM loaded objects cache). But you can control script memory usage by tools like monit and restart your script when mempry limit reaches some point or start script again when your script unexpectedly shuts down.

0

精彩评论

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

关注公众号