Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of PHP timer

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Xiaobian to share with you PHP timer sample analysis, I believe most people do not know how, so share this article for everyone's reference, I hope you read this article after a great harvest, let's go to understand it!

PHP timer that.

There are two common timers: one that is executed periodically, such as a report at 3 a.m. every day; the other that is executed after a specified time (once), such as a daily login reward issued five minutes after a member logs into the system. The two cases correspond to cron and at commands in the shell, similar to setInterval and setTimeout functions in JavaScript (strictly speaking, setInterval is executed periodically, and execution at a specified time point needs to be handled by itself).

PHP programmers who do web development should be familiar with both timer functions in JavaScript, but going back to PHP is a bit dumbfounded: there is sleep in PHP, but there is no (built-in) timer function available. The sleep function barely does this, but it causes the process to block and nothing else (or no response) can be done. Why doesn't PHP provide a timer?

reason

Personally, the essential reason PHP cannot use timers in web development is the lack of a controlled resident memory runtime environment. Two key points: the first is resident memory, and the second is controllable. In CGI mode, the process exits directly after executing the script, and cannot be expected to run the task until the specified time; in PHP-FPM mode, the process (the vast majority) resides in memory, but it is uncontrollable.

Uncontrollable means that the process executing PHP is not affected by PHP code, and the entry point and exit timing of the process are controlled by additional programs. For example, in FPM mode, the exit and die functions in PHP scripts only interrupt the execution of scripts and do not have a special impact on the process of executing scripts (except for memory leaks). PHP developers write scripts that are executables of processes and are unloaded from the execution context of the process when they are finished. In this case, the timing of executing PHP scripts is still externally driven, and PHP code sits peacefully on the hard drive without external requests, doing nothing, and scheduling tasks.

Since PHP is mainly for web development, PHP is a stable and reliable execution mode with fast development efficiency. For example, omitting the resource release step avoids a lot of workload and pits in development. Think about some third-party library code change time zone, character encoding and so on are not restored, in the resident memory running environment will almost certainly lead to subsequent requests have problems. However, in FPM mode, this pit is inadvertently flattened directly, saving a lot of debugging time and making a big contribution to the programmer's hairline preservation.

Now that the question is clear, how do you use timers to perform timed tasks in PHP?

dangerous practice

PHP scripts default to timeouts in web environments. Remove the timeout and you can keep the program running in the background (if the process doesn't exit). For example, the following code continues to run in the background after responding to requests and outputs time-to-file once every five seconds:

# test.phpset_time_limit(0); #unset timeout to allow script to run forever echo 'This is a background run forever script. Now you can leave me alone. ';fastcgi_finish_request(); #End current request do{ file_put_contents("/tmp/out.dat", "test script, now:" . date("Y-m-d H:i:s") . "\n", FILE_APPEND); sleep(5);}while(true);

After requesting the http://localhost:8080/test.php file, monitor the/tmp/out.dat file and find that there is constant content output, regardless of whether the client disconnects, closes the browser, or restarts the computer (the server cannot be restarted). This shows that the program has been executing and that we have achieved the timer function we want. If you change sleep to ussleep, time_nanosleep, you can also implement microsecond and nanosecond timers, isn't it beautiful?

In practice, you should avoid implementing timers in this way, not only because it is inefficient, but also because it is slightly dangerous. One of the reasons is that each request will occupy a process, and it takes 100,000 processes to request 100,000 times, which basically leads to system crash or no response to subsequent requests; in addition, if the session is opened, but the session_write_close is forgotten, subsequent requests of the same user will be hung (the session is locked when it is active, and if the session is not closed, subsequent processes will not be able to open the session).

Web development should respond to user requests as quickly as possible, and forcing timers in web development in this way can leave the entire web application unstable, unreliable, or unpredictable. Mencius said: knowledge and cautious behavior, a gentleman does not stand under a dangerous wall. Unreliable practices should be avoided as much as possible, and by the way, back pan and pan should be avoided.

Next, look at the correct posture for using timers in PHP.

the correct posture

PHP timer implementation can be summarized as follows:

Use scheduling tools such as cron and Jenkins to do periodic timed tasks (either executing scripts or requesting a URL);

One-time execution tasks are delivered to third-party programs through message queues, databases, etc.

Simulate timed tasks like WordPress, but remember that this approach depends on client requests and needs to handle process concurrency issues yourself;

Run PHP programs in memory resident mode, CLI mode.

Except for the third method, other methods are recommended. Please combine the specific scheme with the actual demand. As a PHP programmer, of course, the preferred way to do it is to use PHP, which is CLI mode.

CLI mode

In good conscience, CLI mode allows PHP to expand a lot of space. In CLI mode, the entry point of the program is the script, and the code can reside in memory, and the process is completely controlled by PHP code. In this form, there are many ways to implement the timer. This article lists several ways to throw bricks and lead jade:

Use swoole, workerman and other frameworks, built-in (high-precision) timer;

Use multi-process (pool)/multi-thread (pool) technology (pcntl, pthreads extensions are only available in CLI mode);

Processing tick or alarm signals;

Use event-driven libraries such as libevent and libev;

Sleep plus loop or implement event loop yourself.

If you want to toss, you can use the 2-5 scheme yourself. If you don't want to toss, swole, workerman and other frameworks are the first choice, stable and reliable.

The above is "PHP timer sample analysis" all the content of this article, thank you for reading! I believe that everyone has a certain understanding, hope to share the content to help everyone, if you still want to learn more knowledge, welcome to pay attention to the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report