I was developing a project(its an Intranet project for a company to check employees is working or not) in rails 4. In that I want to take the screen shots of the users logged in every 1 minute and save to server. I created methods for taking screen shot.And could save to the database.But problem is occurring in the cron tab creation. Its not executing at all.
For creating crontab I used gem 'whenever', :require => false in my gem file. After that I wheneverize .it, So I got schedule.rb file.
My schedule.rb file
set :environment, 'development'
every 1.minutes do
runner "MyModel.cron_screenshot"
end
I want to check in development mode thats why I set environment to 'development'
MyModel is my model file contains this code
class MyModel < ActiveRecord::Base
has_attached_file :file_avatar, :default_url => "/files/:style/missing.jpg",
:styles => {
:thumb => "100x100#",
:small => "150x150>",
:medium => "500x500"
}
do_not_validate_attachment_file_type :file_avatar
def self.cron_screenshot
puts pwd()
result = %x{scrot}
create
end
def create
f = File.open(Rails.root.join('screenshot.png'), 'rb')
model = MyModel.new
model.file_avatar = f
model.save
end
end
I am using Ubuntu 13.04 as my operating system. When I entered command crontab -l to check I got the output as
# Begin Whenever generated tasks for: store
* * * * * /bin/bash -l -c 'cd /home/project/screenshot/image && bin/rails runner -e development '\''MyModel.cron_screenshot'\'''
# End Whenever generated tasks for: store
After one minute nothing is happening. What went wrong here?
Related
Does anyone have experience/success using the whenever gem on aws opsworks? Is there a good recipe? Can I put that recipe on a separate layer and associate one instance with that additional layer? Or is there a better way to do it? Thanks!!!
EDIT:
We ended up doing it a bit differently...
Code:
Can’t really post the real code, but it’s like this:
in deploy/before_migrate.rb:
[:schedule].each do |config_name|
Chef::Log.info("Processing config for #{config_name}")
begin
template "#{release_path}/config/#{config_name}.rb" do |_config_file|
variables(
config_name => node[:deploy][:APP_NAME][:config_files][config_name]
)
local true
source "#{release_path}/config/#{config_name}.rb.erb"
end
rescue => e
Chef::Log.error e
raise "Error processing config for #{config_name}: #{e}"
end
end
in deploy/after_restart.rb:
execute 'start whenever' do
cwd release_path
user node[:deploy][:APP_NAME][:user] || 'deploy'
command 'bundle exec whenever -i APP_NAME'
end
in config/schedule.rb.erb:
<% schedule = #schedule || {} %>
set :job_template, "bash -l -c 'export PATH=/usr/local/bin:${PATH} && :job'"
job_type :runner, 'cd :path && bundle exec rails runner -e :environment ":task" :output'
job_type :five_runner, 'cd :path && timeout 300 bundle exec rails runner -e :environment ":task" :output'
set :output, 'log/five_minute_job.log'
every 5.minutes, at: <%= schedule[:five_minute_job_minute] || 0 %> do
five_runner 'Model.method'
end
We have a whenever cookbook in our repo we use that you would be more than welcome to use here: https://github.com/freerunningtech/frt-opsworks-cookbooks. I assume you're familiar with adding custom cookbooks to your opsworks stacks.
We generally run it on its own layer that also includes the rails cookbooks required for application deployment (while not the app server):
Configure: rails::configure
Deploy: deploy::rails whenever
Undeploy: deploy::rails-undeploy
However, we usually also deploy this instance as an application server, meaning we do end up serving requests from the box we're using for whenever as well.
There is one "gotcha", in that you must set your path in the env at the top of the schedule.rb like this:
env :PATH, ENV['PATH']
I've got a problem with a custom paperclip processor within my rails app. I upload a soundfile and the processor creates an waveform image via a shell command (provided by this gem)
I'm running RoR 3.2.7 / Ruby 1.9.3 on Ubuntu 12.04 (production environment). My model with paperclip attachment looks like the following:
# encoding: utf-8
class Track < ActiveRecord::Base
has_attached_file :original_file,
:styles => { :waveform_image => { :waveform => true } },
:processors => [:sound_processor],
:storage => :s3,
:s3_credentials => "#{Rails.root.to_s}/config/s3.yml",
:url => ":s3_eu_url",
:path => "sounds/:id/:five_digit_id_:basename_:style.:extension"
end
The corresponding Paperclip Processor:
class Paperclip::SoundProcessor < Paperclip::Processor
def initialize file, options = {}, attachment = nil
# cut for brevity
end
def make
src = #file
dst = Tempfile.new([#basename, #current_format])
dst.binmode
if #waveform
cmd = "waveform #{File.expand_path(src.path)} #{File.expand_path(dst.path)}"
Paperclip.log(cmd)
out = `#{cmd}`
dst = File.open "#{File.expand_path(dst.path)}"
end
dst
end
end
When the command
waveform #{File.expand_path(src.path)} #{File.expand_path(dst.path)}
is getting executed on the production machine (Ubuntu 12.04), the following error comes up:
/usr/bin/env: ruby: No such file or directory
However the usr/bin/env is a file instead of an directory. Since there is no ruby executable, how can I pass the right location when executing the shell command?
PS: On my development machine (OSX), on usr/bin/env is a copy of my rails app directory. It's working like a charm in development. I appreciate your help!
The error message is indicating that the ruby executable was not found. It is not related to the code that you have included in the question as of now.
The error is coming from the script file that includes the waveform #{File.expand_path(src.path)} #{File.expand_path(dst.path)} line.
Check out these answers to the issue:
- https://stackoverflow.com/a/6126419/429758
- https://stackoverflow.com/a/5241638/429758
- https://stackoverflow.com/a/5241593/429758
- https://stackoverflow.com/a/1064319/429758
They should give you some idea as to why the ruby executable is not being found on your production environment.
I followed the railscast http://railscasts.com/episodes/164-cron-in-ruby but I cant seem to make it worked.
I have schedule.rb in my config.
I wished to refresh my Database.count everyday in my homepage.
I cannot find the deploy.rb in my folder. Where is it?
For testing purpose, I changed it to every 2 seconds.
[schedule.rb]
every '2 * * * *' do
rake "pages_controller:home"
end
[pages_controller.rb]
class PagesController < ApplicationController
def home
#title = "Home"
#companies = Company.find(:all, :limit => 20)
#count = Company.count
end
I have put
gem 'whenever', :require => false
in my gemfile. What have gone missing?
I have used cron job but i run it as rake task please you can try it
every 3.minutes do
set :environment, 'development'
rake "daily",:output => {:error => 'error.log', :standard => 'cron.log'}
end
And my task is like
require 'rubygems'
task :daily => :environment do
puts "i am fine"
# do your code
end
If cron job run fine then there will be nothing in cron.log.Otherwise it will show you if
any error occurs and this file will be generate in your app root directory.
try it..
So... Couple things.
You need a Capfile and a config/deploy.rb to deploy your code using Capistrano and Whenver. You get this by running capify . ... You should most likely watch the railscast on capistrano deployment
Whenever is using configured like:
schedule.rb
every 1.day, :at => '4:30 am' do
runner 'Rails.cache.clear'
end
I really don't think rake "pages_controller:home is going to work unless this is something you've already created elsewhere. I'm further assuming you are caching this page, and that's why you need to refresh the cache.
Finally, you're setting your environment to development, which makes me think you are not deploying this, but instead just wanting to reset the cached home page... So just run rake cache:clear
I can find little to no documentation on this, nor any help from EngineYard.
This is my delayed_job/recipes/default.rb :
if ['solo', 'app', 'app_master'].include?(node[:instance_role])
# be sure to replace "app_name" with the name of your application.
run_for_app("HQ_Channel2") do |app_name, data|
# this is something trip added. beware.
worker_count = 3
worker_count.times do |count|
template "/etc/monit.d/delayed_job#{count+1}.#{app_name}.monitrc" do
source "delayed_job_worker.monitrc.erb"
owner "root"
group "root"
mode 0644
variables({
:app_name => app_name,
:user => node[:owner_name],
:worker_name => "delayed_job#{count+1}",
:framework_env => node[:environment][:framework_env]
})
end
end
# this is something trip removed. beware.
#worker_name = "delayed_job"
# The symlink is created in /data/app_name/current/tmp/pids -> /data/app_name/shared/pids, but shared/pids doesn't seem to be?
directory "/data/#{app_name}/shared/pids" do
owner node[:owner_name]
group node[:owner_name]
mode 0755
end
template "/etc/monit.d/delayed_job_worker.#{app_name}.monitrc" do
source "delayed_job_worker.monitrc.erb"
#owner node[:owner_name]
#group node[:owner_name]
owner "root"
group "root"
mode 0644
variables({
:app_name => app_name,
:user => node[:owner_name],
:worker_name => worker_name,
:framework_env => node[:environment][:framework_env]
})
end
bash "monit-reload-restart" do
user "root"
code "monit reload && monit"
end
end
end
Then I do ey-recipes upload -e production && ey-recipes apply -e production.
Everything goes through.
But when I ey deploy -e production, I get a
Beginning deploy for 'HQ_Channel2' in 'production' on server...
Application master's status is not "running" (green); it is "error".
I checked out my custom log and it returns :
[Thu, 01 Dec 2011 06:07:17 -0800] INFO: Starting Chef Solo Run
/usr/local/ey_resin/ruby/lib/ruby/gems/1.8/gems/chef-0.6.0.2/lib/chef/recipe.rb:196:in `method_missing': Cannot find Chef::Resource::Template for template (NameError)
Why am I getting this error?
Take a look at this answer (written by someone else).
https://gist.github.com/334674
I want to run Paperclip on all files in a directory on the server. Basically, I would like to allow users to FTP some files to my webserver, then I can manually run a rake task to have Paperclip process all of the files (resize the images, update the database, etc).
How can I do this?
I'm not sure if I understood your question - are you asking to run the rake task remotely or how to import images?
In the later case there is an answer.
First you need some Model to keep the images and maybe some other data, something like this:
class Picture < ActiveRecord::Base
has_attached_file :image, :styles => {
:thumb => "100x100>",
:big => "500x500>"
}
end
You can create simple rake task in your lib/tasks folder (you should name the file with .rake extension)
namespace :import do
desc "import all images from SOURCE_DIR folder"
task :images => :environment do
# get all images from given folder
Dir.glob(File.join(ENV["SOURCE_DIR"], "*")) do |file_path|
# create new model for every picture found and save it to db
open(file_path) do |f|
pict = Picture.new(:name => File.basename(file_path),
:image => f)
# a side affect of saving is that paperclip transformation will
# happen
pict.save!
end
# Move processed image somewhere else or just remove it. It is
# necessary as there is a risk of "double import"
#FileUtils.mv(file_path, "....")
#FileUtils.rm(file_path)
end
end
end
Then you can call manually rake task from the console providing SOURCE_DIR parameter that will be the folder on the server (it can be real folder or mounted remote)
rake import:images SOURCE_DIR=~/my_images/to/be/imported
If you are planning to run this automatically I'd recommend you to go for Resque Scheduler gem.
Update: To keep things simple I've deliberately omitted exception handling