简体   繁体   English

检测Cron作业是否正在登台服务器上运行

[英]Detecting if a Cron job is running on a staging server

I'm building a website that will run a series of cron tasks daily to update information in a database that is then used in the site. 我正在建立一个网站,该网站每天将运行一系列cron任务,以更新数据库中的信息,然后该数据库将在该网站中使用。 I have three environments setup: development (my computer), staging and live. 我有三种环境设置:开发(我的计算机),暂存和实时运行。 Both staging and live are accounts on shared hosting. 暂存和实时都是共享主机上的帐户。 The problem I have is in deciding which database access credentials to use depending on which environment the code is running on. 我遇到的问题是,根据代码所运行的环境来决定使用哪个数据库访问凭据。 Ideally all three would have the same credentials but as both staging and live are on a shared server I can't control the name of the database. 理想情况下,这三个名称应具有相同的凭据,但由于暂存和实时都位于共享服务器上,所以我无法控制数据库的名称。 I've mirrored the live database name and access credentials on my own computer but I can't do this on staging. 我已经在自己的计算机上镜像了实时数据库名称和访问凭据,但是我无法在暂存中执行此操作。

What I want to do is to automatically select the correct credentials for the correct environment when my cron task runs, something like this: 我想做的是在执行cron任务时自动为正确的环境选择正确的凭据,如下所示:

if(environment === staging) {
  //define db access constants for staging here
 else {
  //define db access constants for live or dev here
}}

Normally for this sort of thing I'd use $_SERVER['SERVER_NAME'] but as this is running in Cron the $_SERVER auto global isn't available. 通常,对于这种事情,我会使用$ _SERVER ['SERVER_NAME'],但是由于它在Cron中运行,因此$ _SERVER自动全局不可用。 How could I detect on which environment a script is running in a cron job? 如何检测cron作业中在哪个环境中运行脚本?

You could put an extra environment variable in the crontab file: 您可以在crontab文件中放置一个额外的环境变量:

STAGING=1

and then check for $_ENV['STAGING'] == 1 . 然后检查$_ENV['STAGING'] == 1

Or even 甚至

HOSTING_ENV=PRODUCTION

and then check for $_ENV['HOSTING_ENV'] == 'PRODUCTION' . 然后检查$_ENV['HOSTING_ENV'] == 'PRODUCTION'

The environment variable solutions that ajreal and gms8994 are both good. ajreal和gms8994的环境变量解决方案都不错。 Another method is to use php_uname() to fetch the current hostname: 另一种方法是使用php_uname()获取当前主机名:

sean@gimmebarvm-sean:~$ php -r 'echo php_uname("n") . "\n";'
gimmebarvm-sean

run your cron via WGET by calling it by a domain rather by PHP command line 通过WGET通过域而不是PHP命令行调用它来运行cron

you will then be able to detect the platform by its domain 然后,您将能够通过其域检测平台

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM