Home Backend Development PHP Tutorial Detailed explanation of several methods of executing tasks regularly in PHP

Detailed explanation of several methods of executing tasks regularly in PHP

Jul 25, 2016 am 08:58 AM

  1. ignore_user_abort(true);

  2. set_time_limit(0);

  3. function write_txt(){

  4. if(!file_exists("test. txt")){
  5. $fp = fopen("test.txt","wb");
  6. fclose($fp);
  7. }
  8. $str = file_get_contents('test.txt');
  9. $str .= " rn".date("H:i:s");
  10. $fp = fopen("test.txt","wb");
  11. fwrite($fp,$str);
  12. fclose($fp);
  13. }

  14. function do_cron(){

  15. usleep(20000000);
  16. write_txt();
  17. }

  18. while(1){

  19. do_cron();
  20. }

Copy code

The two key functions: ignore_user_abort(true), the function of this function is that the following code will be executed regardless of whether the client closes the browser. set_time_limit(0), the function of this function is to cancel the execution time of the PHP file. If there is no such function, the default PHP execution time is 30 seconds, which means that after 30 seconds, the file will say goodbay.

In addition, usleep supports Windows operating system after PHP5.0.

When we are doing a PHP email sending problem, we often encounter this problem, that is, users subscribe to some information that needs to be sent to the user's mailbox regularly. I searched the Internet and found that there are not many articles like this. This article introduces A method implemented using PHP. The author has not been using PHP for a long time. Everyone is welcome to PP.

1. To achieve scheduled sending, the main problem to solve is timing. What kind of if should be added when writing a program? If a certain time = a certain time, then the page will be sent. However, to implement this process, the problem is that we have to execute this page before it can be sent. Therefore, the main problem to be solved is how to deliver the goods when the time comes The server executes this page regularly, which seems to be difficult to implement.

2. Open the php manual and find the command line mode of PHP. You can study it.

3. Solution: 1. On the Windows platform, you can associate the double-click attributes of cliphp.exe and .php files, or you can write a batch file to execute scripts with PHP. We put the written program in a directory as follows:

  1. E:web Timesend.php
  2. #!/usr/bin/php
  3. require_once("E:webincludesconfig.php");
  4. require_once("E:webincludesclassmail.class.php" );
  5. require_once("E:webincludesclasssmtp.class.php");
  6. // +------+
  7. //Database configuration
  8. $dbhost = "localhost";
  9. $dbport = "3306";
  10. $ dbname = "";
  11. $dbuser = "";
  12. $dbpawd = "";
  13. // +---------+
  14. //Database connection object
  15. $db = new dbLink($dbhost,$ dbport,$dbuser,$dbpawd,$dbname);
  16. $query = "SELECT * FROM wl_mailtemplate WHERE mt_name = 'UserUpdate'";
  17. $mailtemplate =$db->dbQuery($query);
  18. $username = 'sdfsdfdsd ';
  19. $sex = "Mr.";
  20. $accounts = "sdfasdfasdfsad";
  21. $password = "sdfsadfsdasdasddssfds";
  22. $message = "
  23. $message = addslashes($message);
  24. eval_r("$message = "$ message";");
  25. $mail = new SendMail('wfits@jbxue.com', $mailtemplate[0]['mt_subject'], nl2br($message));
  26. if ($mail->Send() )
  27. {
  28. $feedback = "The modification confirmation message has been sent to your registered email, and the current login has been logged out. \nPlease check the confirmation email and obtain a new login password. ";
  29. echo $feedback;
  30. }
  31. ?>
Copy the code

Write a bat file.

  1. @D:phpcliphp.exe E:webmail.php >d:phpclisendmail.log
  2. Pause
Copy code

Save it as: timesend.bat and place it in the @D:phpcliphp.exe directory

Add a scheduled task in window and that’s it!

5. Explanation. 1. The template I use to send emails is stored in the database. There are two other email sending classes that are not provided. If you want, you can contact me. 2. Use absolute paths when using requrie_once. 3. PHP's command line mode allows PHP scripts to run completely independently of the WEB server, so it can reduce the load on the server when sending a large number of emails. 4. Once again, I recommend that you read the PHP manual Chapter 23. PHP command line mode.

Actually, this is not a real way to automatically send emails, but in the WEB mode without desktop applications, this may be a better way~! , I want a system that truly realizes automatic sending of emails, in the service There is still a desktop application for support on the server side! So this automatic sending of emails is just a way to implement PHP programs to send emails!

  1. " . $mailtemplate[0]['mt_message']. "

  2. ";
  3. ignore_user_abort(); // Even if the Client is disconnected (such as closing the browser ), the PHP script can also continue to execute.
  4. set_time_limit(0); //The execution time is unlimited. The default execution time of PHP is 30 seconds. Through set_time_limit(0), the program can be executed without limit
  5. $interval=20 ; // Time interval unit is seconds
  6. $key_file="key.txt"; // Configuration file

  7. if (isset($_GET['s']))

  8. {
  9. if ($ _GET['s']=="0"){ // Stop working, but don't exit
  10. $s="false";
  11. echo "Function is off";
  12. }
  13. elseif ($_GET['s']= ="1"){ // Work
  14. $s="true";
  15. echo "Function is on";
  16. }
  17. elseif ($_GET['s']=="2"){ // Exit
  18. $s ="die";
  19. echo "Function exited";
  20. }
  21. else
  22. die("Err 0:stop working 1:working 2:exit");
  23. $string = "";
  24. write_inc($key_file,$string,true);
  25. exit();
  26. }

  27. if(file_exists($key_file)){

  28. do {
  29. $mkey = include $key_file;
  30. if ($mkey=="true"){ // If it works
  31. ////////// workspace////////
  32. $showtime= date("Y-m-d H:i:s");
  33. $fp = fopen('func.txt','a');
  34. fwrite($fp,$showtime."n");
  35. fclose($fp);
  36. ////////////////
  37. }
  38. elseif ($mkey=="die"){ // If exit
  39. die("I am dying!");
  40. }
  41. sleep ($interval); // Wait for $interval minutes
  42. }while(true);
  43. }
  44. else
  45. die($key_file." doesn't exist !");
  46. //by bbs.it-home.org
  47. function write_inc($path,$strings,$type=false)

  48. {
  49. $path=dirname(__FILE__)."/".$path;
  50. if ($type==false)
  51. file_put_contents ($path,$strings,FILE_APPEND);
  52. else
  53. file_put_contents($path,$strings);
  54. }
  55. ?>

Copy code


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

See all articles