Timeout a function in PHP

后端 未结 7 2019
时光说笑
时光说笑 2020-11-29 07:43

Is there a way to timeout a function? I have 10 minutes to perform a job. The job includes a for loop, here is an example:



        
7条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-29 07:59

    You could try implementing this using 'curl'. Curl is -- from PHP -- mostly used to do HTTP/FTP stuff, but it supports many more protocols, including ssh/sftp. I've never done something ssh/sftp related using curl, so i can not give any additional advice, but you should be able to find additional information here on stackoverflow or somewhere else.

    There is an option "CURLOPT_TIMEOUT" you could use to configure the timeout for your request (there's also an option "CURLOPT_CONNECTTIMEOUT"). You can even specify the timeouts in millisecond resolution (CURLOPT_TIMEOUT_MS / CURLOPT_CONNECTTIMEOUT_MS).

    Anyway: for a cronjob i would recommend to use an additional "lock-file" your script writes when it's started and removes, when it's finished running. You can check for this lock-file within your script so if cron triggers your script before the last run finished, you can just exit your script without any further doing. That ensures, that your script will not be executed multiple times in parallel.

    You can find more on the CURL options and CURL itself in the PHP documentation, too:

    • http://www.php.net/manual/en/function.curl-setopt.php
    • http://www.php.net/manual/en/book.curl.php

    You have to make sure, that your installed libcurl and/or curl for php supports SSH/SFTP, though:

    • SFTP from PHP - undefined constant CURLOPT_PROTOCOLS and CURLPROTO_SFTP?
    • SFTP from within PHP

    etc.

    Hope that helps ...

提交回复
热议问题