【发布时间】:2017-11-09 10:39:27
【问题描述】:
我只是想让一个函数在特定时间运行,但我运气不佳。让我简单介绍一下我所做的基本工作
#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 留在那里,那么它可以正常工作。所以我肯定在这里用延迟功能做错了。
【问题讨论】: