我有一个每天运行的小型PHP Cron作业,可从API获取文件并将其保存到静态文件。
file_put_contents("api.json", fopen("http://example.com/api", 'r'));
Run Code Online (Sandbox Code Playgroud)
该JSON的内容如下所示:
{
recipes: [
{
id: 30476,
title: "Selfmade Chicken Nuggets",
...
},
{...} ]
}
Run Code Online (Sandbox Code Playgroud)
我的问题:我想创建“每日食谱”逻辑。
因此,我想每天用食谱创建一个额外的数组。
在最好的情况下,我想要这样的东西:
第1步:创建一个包含所有配方的“剩余配方阵列”
步骤2:每天从剩余的食谱数组中获取3个食谱,并将它们放入某种“当日食谱”数组中
步骤3:如果剩余的食谱阵列为空或没有3个元素,请从食谱中重新填充
我的Javascript客户端中已经有了该逻辑:
let fullRecipeList = await this.appData.getRecipeList();
let recipesOfTheDay = await this.appData.getItem("recipesOfTheDay");
let recipesOfTheDayValidUntil = await this.appData.getItem(
"recipesOfTheDayValidUntil"
);
let remainingRecipes = await this.appData.getItem("remainingRecipes");
if (!remainingRecipes || remainingRecipes.length < 3) {
remainingRecipes = this.shuffleArray(fullRecipeList);
}
if (
recipesOfTheDay &&
moment(recipesOfTheDayValidUntil).isSame(new Date(), "day")
) {
this.recipeList = recipesOfTheDay;
} else {
recipesOfTheDay = remainingRecipes.splice(0, 3);
this.recipeList = recipesOfTheDay;
await this.appData.setItem("remainingRecipes", remainingRecipes);
await this.appData.setItem("recipesOfTheDay", recipesOfTheDay);
await this.appData.setItem(
"recipesOfTheDayValidUntil",
moment().startOf("day")
);
}
Run Code Online (Sandbox Code Playgroud)
是否可以在服务器端cron作业中创建这种逻辑?
代码看起来如何?我对整个PHP世界都是陌生的:)
小智 1
有时如果你php直接使用cron,环境上下文会有所不同,并且文件可能会出现问题:无法找到文件进行读取,或者文件可能会写入到奇怪的位置。
我在 cron 作业中所做的是直接使用wget或类似的实用程序调用 Web 服务:
# every day at eight run recipes of the day
* 8 * * * wget -q -O /dev/null 'https://www.server.com/recipesOfTheDay.php'
Run Code Online (Sandbox Code Playgroud)
您甚至可以用作localhost您的服务器名称。
然后,您的脚本可以将修改后的内容保存到本地 JSON 文件或其他文件中。