Reputation: 3164
I've created a module that starts a Thread which sends out emails ever 5 minutes. I start the thread by running a rake task once which loads in a module which starts the thread like this:
require "#{Rails.root}/app/lib/Cron.rb"
namespace :cron_starter do
desc "TODO"
task start: :environment do
Cron.run
end
end
The code Cron.run
calls my module method that starts the thread which runs an infinite loop. All of this works fine, but what do I do if I need to kill the thread? Is there a way to attach to the thread via another rake task and kill it? I could always write to a basic txt file and kill it that way based on flag, but that doesn't seem very elegant. Thanks in advance.
UPDATE
I tried
ps aux | grep cron_starter:start
the output I got was
root 11358 0.0 0.0 12944 1088 pts/0 S+ 14:30 0:00 grep --color=auto cron_starter:start
I'm not real sure if any of the numbers are process ids, so I attempted to run
kill -9 11358
kill -9 12944
The CLI responded with No such process
UPDATE 2
I've tried printing Thread.current.object_id to a log file and I've attempted to kill the thread from this ID as well but again I get the same error as above.
Upvotes: 0
Views: 718
Reputation: 3164
So I figured it out finally. The problem was that I was launching a new Thread
and not a new Process
I fixed the issue by creating a new process like this:
Process.fork do
#my code here that loops forever
logProcess(Process.pid) #this function is an external function that I created that writes the parameter to a file.
#you can use the id from Process.id to kill the process from the CLI.
end
You can kill the process by getting the value of Process.id
and running
kill -9 process_id_goes_here
Upvotes: 0
Reputation: 4080
I would install and use sidekiq for this. It comes with a dashboard and you can configure cron via the gem sidekiq-scheduler. You can then quiet or kill the job queue from the dashboard, which will stop the emails. Honestly, if you have cron jobs on ROR you should have an active job extension like sidekiq anyways.
Baring that, I would indeed write the pid to a text file and kill via the pid.
Upvotes: 0