【问题标题】:How to make a cron job to save from PHP Smarty Index.tpl to Index.html?如何进行 cron 作业以将 PHP Smarty Index.tpl 保存到 Index.html?
【发布时间】:2021-10-03 04:17:31
【问题描述】:

我想节省一些服务器资源,并从每天更新的 Smarty 模板 index.tpl 创建一个静态 index.html 文件。

让 cron 作业实现这一目标的最佳方法是什么?

【问题讨论】:

  • 渲染模板?顺便说一句,Smarty 具有内置的缓存功能...
  • @LarsStegelitz 哦,真的吗?我是新来的。它是自动的还是我需要做点什么?
  • 考虑您正在使用的版本的 Smarty 文档。您需要正确配置它,但这应该不难弄清楚。
  • 我也在考虑 Smarty 缓存,但我一直认为是关于将 Smarty 语法转换为 PHP 可执行文件来替换模板本身。在模板中生成和插入的所有变量都可能需要一些计算时间(SQL 查询、计算等),如果是这样,那么如果您知道 cron 任务只需要每天更新,它似乎是减少负载的好方法。静态 HTML 文件总是比启动 PHP、Smarty 等更快。静态文件也更安全。您还可以设置 HTTP 缓存标头并使用 Varnish 来减少负载。
  • @PatrickJanser 谢谢。我陷入了另一个问题。本周末将对其进行测试并相应地标记它。谢谢!

标签: php cron smarty


【解决方案1】:

嗯,这取决于您是否可以在命令行 (CLI) 中运行 php,或者不能在服务器上运行。您可能需要找到php 可执行文件的路径,因为它可能未在PATH 中设置。

如果是,那么我将使用 php update-index.php 运行一个自制脚本,该脚本会重新生成您的 index.html 文件。

如果您无法在 CLI 中运行 PHP,那么您可以将此脚本放在您的网站上并使用 curlwget 调用它。您可以使用 Apache 规则或仅通过检查 POST 参数的存在来保护它,如下所示:

<?php

define('API_KEY', '732hCwhjK');

// If the key is missing then just stop execution.
if (!isset($_POST['key']) || $_POST['key'] !== API_KEY) {
  die();
}

// TODO: update your index.html file with Smarty.
// Don't print anything so that the cron doesn't send any mail.
// If you get an error then print it here.
// Cron will then send you the mail with the content printed out.

cron 配置文件示例:

MAILTO="your.mail@example.com"

# CRON TASKS SYNTAX
# -----------------
#
# Output dumper: >/dev/null 2>&1
#
# Multiple values with commas: 5,25,45
#
# Every X intervals: */10 * * * * for every 10 minutes
#
# Aliases: @reboot  = run once at startup
#          @hourly  = 0 * * * *
#          @daily   = 0 0 * * *
#          @weekly  = 0 0 * * 0
#          @monthly = 0 0 1 * *
#          @yearly  = 0 0 1 1 *

# Execute update-index.php twice a day, at 6am and 6pm:
0 6,18 * * * /bin/php /home/user/www-data/site/update-index.php 2>&1

# Execute update-index.php via calling the URL at 3am.
# Key is sent via POST to avoid having it visible in the log files.
0 3 * * * wget -O - -q -t 1 --post-data="key=732hCwhjK" "https://your-site.com/update-index.php"

编辑 cron 选项卡

crontab -e -u username
如果你想定义编辑器(nano 或 vim),前缀 EDITOR=xxxx 如下:

EDITOR=vim crontab -e

用户 crontab 文件在这里:

/var/spool/cron/crontabs/

Crontab 文件也可以存储在:

/etc/cron.d/
/etc/cron.hourly/
/etc/cron.daily/
/etc/cron.weekly/
/etc/cron.monthly/

它们在以下时间运行:

grep run-parts /etc/crontab

或者只是检查所有内容:

less /etc/crontab

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-12
    • 2011-05-02
    • 2015-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多