问题
In my application, I want to invoke an action every two weeks based on when the user triggered an action. I guess what's confusing is why there doesn't seem to be a straight forward way of doing this.
Ideally, the repeated job would be set in the model, not some other file. For example, the whenever
gem has these instructions:
Getting started
$ cd /apps/my-great-project
$ wheneverize .
This will create initial
config/schedule.rb
file for you.
But I don't want to put my schedules in there. I want the schedule to be in my model. The schedule isn't being set by me, it's being set by my users.
Is there any straightforward way of implementing this? I've been stumped on this for weeks.
回答1:
You could use delayed-job.
http://asciicasts.com/episodes/171-delayed-job
Your users could define jobs that are stored in your model. You would create the first delayed job and after each completed job you can start a new delayed job.
If your user creates a job that should run at 3:00 am and he saves that job at 3:00 pm you need to create the first job:
Delayed::Job.enqueue(CronJob.new(params[:id]), 1, 12.hours.from_now )
Before starting this job you would create tne next job
Delayed::Job.enqueue(CronJob.new(params[:id]), 1, 1.days.from_now )
来源:https://stackoverflow.com/questions/18814342/rails-making-new-cron-jobs-based-on-user-input