Php, wait 5 seconds before executing an action

Php, wait 5 seconds before executing an action

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

The Illusion of Synchronous Delays in PHP Scripts

You want to automate a multi-step export process on shared hosting, specifically introducing pauses between file generation steps. Your current manual workflow involves chaining URLs: script.php?start=0&end=500, then script.php?start=501&end=1000, and so on. You are asking how to replace this manual iteration with a single button click that executes the first batch, waits five seconds, executes the second, waits again, and finishes the third.

The short answer is: you cannot do this effectively within a standard PHP script execution context.

When you request script.php from a browser or a CLI cron job, the PHP engine follows a strict request-response cycle. It executes your code until it hits a fatal error, a shutdown function, or the maximum execution time limit (max_execution_time). Once the script finishes, the process terminates immediately. There is no native mechanism in PHP to say "pause for 5 seconds and keep this process alive" while waiting for the next logical step within the same request lifecycle.

If you simply insert sleep(5); into your loop before generating the next file, two things will likely happen on shared hosting:

  1. Timeout: The script will exceed the server's execution time limit (often set to 30 or 60 seconds) before it can finish all three steps. You will get a blank page or a "502 Bad Gateway" error.
  2. Resource Waste: Shared hosting environments aggressively kill processes that consume CPU or block I/O for too long without returning data to the client.

The Architecture of Asynchronous Tasks

To solve this, you must decouple the trigger from the execution. You cannot run a sequence of heavy database queries with artificial delays in a synchronous request. Instead, you need to offload the work to a background job queue.

Laravel provides an elegant solution for this via its Task Scheduler and Queue system. By moving your export logic out of the direct HTTP request path, you can handle the timing without hitting execution limits.

Here is how you should restructure the logic:

  1. The Trigger: Your script.php (or a Laravel route) no longer loops through the data. Instead, it receives the button click and dispatches a single job to the queue.
  2. The Job: A queued job handles the iteration. Inside the job, you can safely call sleep(5) because the worker process is designed to run until completion without strict request timeouts.
  3. The Execution: The queue worker picks up the job and processes the batches sequentially.
// app/Jobs/ProductExportQueueJob.php
namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class ProductExportQueueJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $startIndex = 0;
    public $endIndex = 500;
    public $fileIndex = 0;
    protected $totalBatches = 3;

    public function __construct($startIndex = 0, $endIndex = 500, $fileIndex = 0)
    {
        $this->startIndex = $startIndex;
        $this->endIndex = $endIndex;
        $this->fileIndex = $fileIndex;
    }

    public function handle()
    {
        // Generate the file for this batch
        $this->generateBatchFile();

        // Only wait if this is not the last batch
        if ($this->fileIndex < $this->totalBatches - 1) {
            sleep(5);
        }
        
        // Logic to determine next batch parameters would go here
    }

    protected function generateBatchFile()
    {
        // Your existing logic to query products and write product{$this->fileIndex}.txt
    }
}

Why This Approach Works on Shared Hosting

The key distinction is that the web server (Apache/Nginx) does not need to wait for the job to finish. It returns an immediate "200 OK" response to your button click and moves on. The actual heavy lifting happens in the background via a cron job running php artisan queue:work.

This architecture respects shared hosting constraints because the main process is lightweight, and the long-running task runs in isolation. If one batch takes too long or hits a limit, it doesn't crash the entire server; it just stops that specific job attempt.

Limitations of Shared Hosting

Even with queues, you must be mindful of resource limits.

  • Execution Time: While queue workers usually have higher limits, some hosts still enforce hard caps. If a single batch query is massive, ensure your database queries are optimized to avoid timeouts.
  • Memory Limits: Loading 500 products into memory and writing them out can spike RAM usage. Ensure you are not loading the entire dataset into an array if it exceeds memory_limit.
  • File System Permissions: On shared hosting, you must ensure the user running your PHP script has write permissions to the directory where product0.txt will be saved.

Conclusion

You cannot achieve a synchronous "click button -> wait -> do next thing" flow within a single PHP request on shared hosting without hitting execution limits or timeouts. The only robust solution is to treat the file generation as an asynchronous job. By dispatching tasks to a queue and using sleep() within the worker process, you can control the timing between batches while keeping your web server responsive and compliant with hosting restrictions.

Our network