Rails 5 调度程序每天更新一次数据库 [英] Rails 5 scheduler to update database once a day

查看:33
本文介绍了Rails 5 调度程序每天更新一次数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Rails 的新手,想每天在午夜运行一次批处理文件/计划任务,以检查哪些条目已过期.表中的每条记录都有一个closures_date,在此之后,此类记录必须处于非活动状态.(DB 上的状态为 active=false).所以基本上它会运行 2 个 SQL 查询来获取所有记录,然后将另一个字段标记为对于过时的记录无效.我正在使用 Rails 5.

I'm new to rails and want to run a batch file/schedule task daily once at midnight that checks which entries have expired. Every record in the table has a closing_date and after that time, such records must be inactive.(status active=false on DB). so basically it will run 2 SQL queries to fetch all records and then flag another field to inactive for records that are outdated.I'm working with Rails 5.

我应该如何处理这个gem(rufus,无论,发条或任何其他gem)还是只是一些用于cronjob的系统工具?我要将我的数据库更改为PostgreSQL,这会产生影响吗?任何人都可以分享任何建议或示例代码以获得想法.

How should I go about this-gem(rufus,whatever,clockwork or any other gem) or simply some system tool for cronjob?I'm going to change my DB to PostgreSQL so will that impact? Any suggestions or sample code anyone can share to get an idea.

推荐答案

简而言之:你可以使用 whenever Gem 为此目的.

In brief: You can use whenever Gem for this purpose.

您需要为您将编写 SQL 的位置创建一个 rake 任务.然后使用任何时候将其安排为 cron 作业

You need to create a rake task for where you will write your SQL. Then schedule it as cron job using whenever

详细说明

第一步是创建一个 rake 任务.您可以使用控制台执行此操作

First step will be creating a rake task. You can do this using the console

rails g task my_namespace my_task1 

这将在 lib/tasks 文件夹中创建一个名为 my_namespace.rake 的文件,其初始内容为

This will create a file named my_namespace.rake in the lib/tasks folder with initial content like

namespace :my_namespace do
  desc "TODO"
  task task1: :environment do
    # Your code will go here
  end

end

您可以通过运行来检查您的任务是否正常运行

You can check whether your task is running properly by running

rake my_namespace:task1 

在控制台中.

现在您需要使用 whenever gem 安排作业.

Now you need to schedule the job using the whenever gem.

  1. gem 'whenever', :require =>Gemfile 中的 false.
  2. 运行捆绑安装
  3. 在终端中运行 wheneverize 命令.这将在 config 文件夹中创建一个 schedule.rb 文件.
  4. 添加以下代码来安排您的抽水任务:

  1. gem 'whenever', :require => false in Gemfile.
  2. Run bundle install
  3. run wheneverize command in terminal. This will create a schedule.rb file in config folder .
  4. Add the following code to schedule your rake task:

every 1.day, at: '8:00 pm' do
  rake "my_namespace:task1"
end

  • 运行此命令:whenever --update-crontab.如果您的环境是开发环境,请使用命令:whenever --update-crontab --set environment='development'(参见 这个问题.

  • Run this command: whenever --update-crontab. In case your environment is development, use command: whenever --update-crontab --set environment='development' (see this question.

    这篇关于Rails 5 调度程序每天更新一次数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆