Table of Contents
Reply content:
Home Backend Development PHP Tutorial How to improve efficiency when PHP performs large-scale tasks?

How to improve efficiency when PHP performs large-scale tasks?

Aug 18, 2016 am 09:15 AM
php

I have a php that schedules tasks to be executed once a day. The logic is as follows:
1. Connect to the database and Select to read relevant data from the database into an array
2. Loop according to the amount of data obtained. The middle of the loop contains 3 mysql operations ( Select, insert, update each)
3. Close the database connection after the loop

The number of loop executions depends on the mysql_num_rows in step 1, which is basically thousands or tens of thousands.
Then during the loop process, thousands of X3 database operations will be performed continuously in a short period of time, which is very inefficient. And because multiple tasks require a long time to complete due to the number of cycles, a 504 error will occur in nginx.
Moreover, frequent database operations and long connections occupy too many resources, resulting in inefficiency of the entire environment.

How to optimize it?
Please give me some advice, thank you in advance

Reply content:

I have a php that schedules tasks to be executed once a day. The logic is as follows:
1. Connect to the database and Select to read relevant data from the database into an array
2. Loop according to the amount of data obtained. The middle of the loop contains 3 mysql operations ( Select, insert, update each)
3. Close the database connection after the loop

The number of loop executions depends on the mysql_num_rows in step 1, which is basically thousands or tens of thousands.
Then during the loop process, thousands of X3 database operations will be performed continuously in a short period of time, which is very inefficient. And because multiple tasks require a long time to complete due to the number of cycles, a 504 error will occur in nginx.
And frequent database operations and long connections occupy too many resources, resulting in inefficiency of the entire environment.

How to optimize it?
Please give me some advice, thank you in advance

For the situation you mentioned, it is recommended not to use requests to solve the problem. Use crontab to add scheduled tasks to run php scripts in the background. When querying the database, process it in batches, for example, a total of 100,000 items, 1,000 items at a time; if it must be processed one by one and the speed is It is not very fast. It is recommended to process while fetch_row, to avoid putting it into the array first and then looping. Remember to set_time_limit and the timeout of the database connection based on the implementation.

A few thoughts on this kind of long-term task with a slightly larger amount of data:
1. The web environment is not suitable for long-term tasks: the architecture of nginx+php-fpm is not suitable for executing long-term tasks, and the middle All kinds of timeouts can torture people to death. Apache+PHP is better at least to control the timeout. A simple set_time_limit(0) can do it.
2. Task scheduling is implemented through the web: Most PHP frameworks do not have good command line support, or they do not consider command line support when implementing it, so a web-based task distribution mechanism will be easier to implement, which will help The existing framework will be much less intrusive, and for a stable project, it is extremely important to ensure a unified entrance. If the task is run under the command line, there are many issues to consider. The most prominent issue is the file permission issue. Generally, web projects are run by users such as apache, and the owner of the generated files is also apache, and apache generally does not Although login is allowed, it is possible to run commands as the apache user, but it is more complicated.
3. Divide and conquer: One solution for dealing with long-term tasks is divide and conquer, splitting large tasks into small tasks, converting long-term tasks into multiple short-term small tasks, reducing the time occupied by resources, and reducing the time required for long-term tasks. Various problems caused by time execution, such as database connection timeout, PHP memory leak, etc.

Attached is an example I wrote, please give me some advice
https://github.com/zkc226/cur...

When a large amount of data is needed, it is handed over to the task system for execution. First, a request is initiated, and the message producer hands the request to the consumer for processing and returns to avoid waiting for a timeout. Consumers perform multi-threaded processing. It is recommended to use Gearman, which is very convenient to use and supports PHP interface. Others like Workman, Swoole, etc. can be implemented.

All operations are concentrated on the same server and executed at the same point in time, which is definitely time-consuming and resource-consuming.
Either process it in batches like @黄红 said.
Or add more servers and put these tasks Distributed to other servers for execution, so-called distributed processing, but it will increase the complexity of the task, because the consistency of the data must be ensured

1. Export data to a file, read the file and loop. (such as mysqldump)
2. Consider whether you can spell the statements first and execute them in batches. Instead of executing every loop.
3. Consider whether stored procedures can be used

And because of the number of cycles, multiple tasks take a long time to complete, which will cause nginx to display a 504 error.

Is it real-time calculation? For tasks with a large amount of calculations, should we consider running tasks in the background to calculate the write cache and request the read-only cache in real time?

This question is a bit like the question I answered before about parallel execution to improve efficiency

The essence is to divert the reading of this big data, and perform modulo parallel execution based on ID. For example, your server and database can withstand 20 concurrent executions

The simplest way to parallelize is to open 20 script processes for execution
0.php -> select * from test where id%20=0;
1.php -> select * from test where id%20=1;
2.php -> select * from test where id%20=2;
....

This is the pulling method.

Another way is to push it to the queue, and then the queue calls the waker process to execute, which is more standardized and easy to manage. For example, there is a mentioned gearman upstairs. When I was working on the SMS platform, I also had daily scheduled tasks, which was used of this.

The logic is probably that you open a scheduled task script to send all the queried data to the gearman scheduler by calling the gearman client, and then you open 20 workers (can be on the same server or on different servers in the LAN) ), and then the scheduler will assign these 20 gearman worker scripts to execute. The code of each worker script is the same, and it is the execution of one piece of data and one task

Use PHP script in cli mode for processing. Do not use WEB method, it is easy to time out

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 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months 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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

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,

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles