我只是想让功能在特定时间运行,但我没有太多运气。让我来看看我所做的基本知识
#Gemfile
gem 'delayed_job_active_record'
#config/application.rb
module SampleApp
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
config.active_job.queue_adapter = :delayed_job
end
end
#Ran from command line
[06.07.2017/15:38:02] user@ubuntu $ rails g delayed_job:active_record
Running via Spring preloader in process 72879
identical bin/delayed_job
chmod bin/delayed_job
create db/migrate/20170607203821_create_delayed_jobs.rb
[06.07.2017/15:38:21] user@ubuntu $ rake db:migrate
== 20170607203821 CreateDelayedJobs: migrating ================================
-- create_table(:delayed_jobs, {:force=>true})
-> 0.0088s
-- add_index(:delayed_jobs, [:priority, :run_at], {:name=>"delayed_jobs_priority"})
-> 0.0051s
== 20170607203821 CreateDelayedJobs: migrated (0.0142s) =======================
好的,所以我的视图上基本上有一个按钮调用post_now
,然后调用我自定义模型中的函数。这是我所拥有的一个例子:
#posts_controller.rb
def post_now
set_post
submit_post = SchedulePost.delay(run_at: 1.minute.from_now).schedule_post(@post)
redirect_to posts_path, flash: {success: submit_post[1] }
end
然后是SchedulePost类,它只是编写一个文本文件(暂时)
#models/schedule_post.rb
class SchedulePost < ActiveRecord::Base
def self.schedule_post(post)
command = "touch #{Rails.root}/public/test.txt"
system(command)
return
end
end
所以我期待发生的事情是,当调用post_now时,它应该在1分钟后运行schedule_post函数,这应该只是写一个文本文件。如果我删除.delay(run_at: 1.minute.from_now)
块并将schedule_post
留在那里,那么它可以正常工作。所以我肯定在这里做了一些错误的延迟函数。
非常感谢任何帮助。
答案 0 :(得分:1)
你需要启动delayed_job worker来执行延迟任务...在你的终端从app根目录执行
rake jobs:work