Table of Contents
Laravel + crontab
添加 crontab 配置
验证任务调度是否正常执行
参考文章
DaoCloud + Docker + Laravel + crontab
具体步骤
完整相关文件
示例(完成代码可以参考下面的项目)
Home Backend Development PHP Tutorial Docker 容器里配置计划任务 crontab(DaoCloud + Docker + Laravel5)

Docker 容器里配置计划任务 crontab(DaoCloud + Docker + Laravel5)

Jun 20, 2016 pm 12:27 PM

一名野生全栈工程师,喜欢研究各种新技术。

Follow Now

最近项目涉及到一个定时任务的功能,所以去这几天研究了一下 crontab 的使用方法,按照网上的相关教程顺利在自己的电脑上成功开启了这个功能

Laravel + crontab

添加 crontab 配置

1、执行命令

$ crontab -e
Copy after login

2、添加以下内容( path/to为应用路径 ),即每分钟去执行一次以下的命令

* * * * * php /path/to/artisan schedule:run >> /dev/null 2>&1
Copy after login

3、启动(以下命令为Ubuntu下的启动命令,其他系统可能不一样)

$ /etc/init.d/cron start
Copy after login

完成以上三步即可以成功开启 Laravel 的任务调度功能了,下面验证一下

验证任务调度是否正常执行

./App\Console\Kernel

...    protected function schedule(Schedule $schedule)    {        $schedule->call(function () {            // 以下代码会插入一条 Tweet 数据            DB::table('tweets')->insert(['content' => 'Hi']);        })->everyMinute();    }...
Copy after login

过几分钟后就可以去查看一下数据库有没有成功插入数据~

参考文章

  • Laravel 任务调度
  • docker下计划任务crontab的使用方法[python]
  • Laravel 定时任务

DaoCloud + Docker + Laravel + crontab

上面的尝试成功后就是将这些配置到 Dockerfile 里,让容器在启动的时间自动开启 crontab 任务调度,让这一切都自动去完成~

具体步骤

1、在项目创建以下 crontab 配置文件 ./_linux/var/spool/cron/crontabs/root

* * * * * /usr/local/bin/php /app/artisan schedule:run >> /dev/null 2>&1
Copy after login
Copy after login

2、在 Dockerfile 里将配置文件复制到 crontab 指定的配置所在目录

FROM php:7.0.7-apacheMAINTAINER JianyingLi <lijy91@foxmail.com># 安装 cron 命令... RUN apt-get update && apt-get install -y cron vim...# 配置 crontab# 复制配置文件 /var/spool/cron/crontabs/ADD _linux/var/spool/cron/crontabs/root /var/spool/cron/crontabs/root# 设置文件所有者和文件关联组为 root:crontab ,关联组必须为 crontabRUN chown -R root:crontab /var/spool/cron/crontabs/root \# 修改文件的权限,必须为 600,否则不认 && chmod 600 /var/spool/cron/crontabs/root# 创建 log 文件RUN touch /var/log/cron.log...# 在 entrypoint.sh 脚本里加入启动 apache 和 crontab 的相关命令RUN chmod 777 ./entrypoint.shENTRYPOINT ["./entrypoint.sh"]
Copy after login

3、添加 ./entrypoint.sh 脚本,并在里面启动 apache 和 crontab

php:7.0.7-apache这个基础镜像已经包含了一个 CMD ['apache2-foreground']指令用于启动 apache 服务,但是我们需要同时启动apache 和 crontab ,所以增加了这个脚本文件并在里面加入了相关的命令。

#!/bin/bashset -x# 将环境变量保存至 /etc/default/localerm -rf /etc/default/localeenv >> /etc/default/locale# 启动 crontab/etc/init.d/cron start# 启动 apacheapache2-foregroundexec "$@"
Copy after login

由于crontab的执行机制,所以无法直接使用通过DaoCloud后台配置的环境变量,但是我们应用的配置都是通过环境变量来配置的,所以需要通过 env 命令将这些环境变量保存到 /etc/default/locale里,crontab 在启动时会加载这个文件里的环境变量,否则在执行 php artisan schedule:run命令会无法获取相关的应用配置,导致无法执照我们预想的去运行(例如始终无法插入新数据到数据库)

完整相关文件

以下是三个主要是配置文件,我是用来构建运行 Laravel5 应用的,应该可以满足大部分的需求。

 .├── _linux│   └── var│       └── spool│           └── cron│               └── crontabs│                   └── root├── Dockerfile└── entrypoint.sh
Copy after login

./Dockerfile

FROM php:7.0.7-apacheMAINTAINER JianyingLi <lijy91@foxmail.com>RUN apt-get update     \ && apt-get install -y \      libmcrypt-dev \      libz-dev      \      git           \      cron          \      vim           \ && docker-php-ext-install \      mcrypt    \      mbstring  \      pdo_mysql \      zip       \ && apt-get clean      \ && apt-get autoclean  \ && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composerADD _linux/var/spool/cron/crontabs/root /var/spool/cron/crontabs/rootRUN chown -R root:crontab /var/spool/cron/crontabs/root \ && chmod 600 /var/spool/cron/crontabs/rootRUN touch /var/log/cron.logRUN a2enmod rewriteWORKDIR /appCOPY ./composer.json /app/COPY ./composer.lock /app/RUN composer install --no-autoloader --no-scriptsCOPY . /appRUN rm -fr /var/www/html \ && ln -s /app/public /var/www/htmlRUN chown -R www-data:www-data /app \ && chmod -R 0777 /app/storage      \ && composer installRUN chmod 777 ./entrypoint.shENTRYPOINT ["./entrypoint.sh"]
Copy after login

./_linux/var/spool/cron/crontabs/root

* * * * * /usr/local/bin/php /app/artisan schedule:run >> /dev/null 2>&1
Copy after login
Copy after login

./entrypoint.sh

#!/bin/bashset -xrm -rf /etc/default/localeenv >> /etc/default/locale/etc/init.d/cron startapache2-foregroundexec "$@"
Copy after login

示例(完成代码可以参考下面的项目)

  • phoenix-backend
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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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,

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.

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 to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

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.

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.

See all articles