Call a task when server starts

hi, I am trying to invoke a task when server start but fails to do that.
Can any body help me that how to do it?
My code is:
path : app_root/lib/tasks/mytask.rake

task :start => :environment do
#do some magic and start the cron
puts “started!!!”
system(“start”)
end
task :stop do
#do some more magic and stop IT
puts “stops!!!”
end

Could you put the code in an initializer?

but how can i run that???

my actual code is like:

task :start => :environment do
#do some magic and start the cron
while true do
#http_request_and_response_code
end
end
task :stop do
#do some more magic and stop IT
puts “stops!!!”
end

I guess it might help to understand what your code is trying to do.

But if this is the code you want to execute when the server starts:

#do some magic and start the cron

You could just put that in an initializer, and it will be executed when the server starts.

I agree with you Tim but I have tried this idea.
Whats happen is server is started but the service on the particular port is not being start because of that forever loop, this one is being problem in my app.

Can u give me any more suggestion? and ya one more thing I don’t want to use Thread class…

Thanks Tim.

That actually makes sense. Rails waits for the initializer to finish running before running the rest of your application. So if you have an infinite loop in there, it’ll never finish running.

Might be best to spawn another process using Thread or just run that code as part of a cron job or other manual process.

Would help to understand what your code is trying to do.

Can you tell me that how many times the server loads all the files?
Because when I start the server it execute the same code multiple times after some period of time.

This is *another* good reason to not try to do this in an initializer
- the process will get launched once for each application instance.
Typically, most deployment setups wind up with more than one instance
(Passenger starts 6 by default, I believe). Some environments will
also shut down idle instances after a period of idleness and then
start more up when traffic appears.

--Matt Jones

Thanks Matt.
Can u tell me that how can i overcome this for my code?