search
HomeBackend DevelopmentPHP TutorialDetailed explanation of several methods of executing tasks regularly in PHP

  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 p>
  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
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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 Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.