dongtan3306 2019-07-07 11:12
浏览 84

每天从带有cron作业的数组中获取3个项目

i have a small PHP Cron Job that runs every day get a file from an API and save it to a static file.

file_put_contents("api.json", fopen("http://example.com/api", 'r'));

The content of this JSON looks like that:

{ 
  recipes: [
  {
    id: 30476,
    title: "Selfmade Chicken Nuggets",
    ...
  }, 
  {...} ] 
}

My issue: I would like to create a "recipes of the day" logic.

Therefore i would like to create an extra array with recipes per day.

In best case I would like to have something like this:

Step 1: Create a "remaining recipes array" that contains all recipes

Step 2: Get 3 recipes per day from the remaining recipes array and put them in some kind of "recipes of the day"-array

Step 3: If the remaining recipes array is empty or don't have 3 elements, refill it from recipes

I already have that logic in my Javascript client:

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")
    );
}

Is it possible to create that kind of logic in my server side cron job?

How would the code look like? I am quite new to the whole PHP world :)

  • 写回答

3条回答 默认 最新

  • duanmanmian7589 2019-07-09 14:45
    关注

    Sometimes if you use php directly in cron, the environmental context is different and there can be issues with files: files can't be found for reading, or files can be written in strange places.

    What I've done in my cron jobs is call web services directly using wget or similar utility:

    # every day at eight run recipes of the day
    * 8 * * * wget -q -O /dev/null 'https://www.server.com/recipesOfTheDay.php'
    

    You can even use localhost as your server name.

    Your script can then save to a local JSON file or whatever with the revised contents.

    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?