巨人の足元でたじlog

そうして言葉を軽んじるから――― 君は私の言葉を聞き逃す

twitter分析アプリ②

バッチ処理をするにはrakeタスクってのを使うみたいだ。

rakeタスクってのは、いままでおまじない的に使っていた

$ be rake db:migrate

※ alias be='bundle exec'
とかで呼び出されるタスクのことらしい。

作り方は簡単。

$ be rails g task task_sample

これで生成されたファイルlib/tasks/task_sample.rake

namespace :task_sample do
end

を、次のように書き換えてみる。

namespace :task_sample do
    desc "実行処理の説明"
    task :sample do
      puts "Hello World"
    end
end

これで、呼び出すときはコンソールから

$ be rake task_sample:sample
Hello World

→OK。Hello Worldが表示されました。
コロンの前が、rakeファイルの名前で、
コロンの後が、taskの名前ということか!

今までの

$ be rake db:migrate

も、dbというrakeファイルの、migrateというtaskを実行していたに過ぎなかったのか〜!
これは学び。
ちなみにrakeタスク一覧はこれで見られると。

be rake -vT
rake about                              # List versions of all Rails frameworks and the environment
rake active_storage:install             # Copy over the migration needed to the application
rake active_storage:install:migrations  # Copy migrations from active_storage to application
rake app:template                       # Applies the template supplied by LOCATION=(/path/to/template) or URL
rake app:update                         # Update configs and some other initially generated files (or use just update:configs ...
rake assets:clean[keep]                 # Remove old compiled assets
rake assets:clobber                     # Remove compiled assets
rake assets:environment                 # Load asset compile environment
rake assets:precompile                  # Compile all the assets named in config.assets.precompile
rake cache_digests:dependencies         # Lookup first-level dependencies for TEMPLATE (like messages/show or comments/_commen...
rake cache_digests:nested_dependencies  # Lookup nested dependencies for TEMPLATE (like messages/show or comments/_comment.html)
rake db:create                          # Creates the database from DATABASE_URL or config/database.yml for the current RAILS_...
rake db:drop                            # Drops the database from DATABASE_URL or config/database.yml for the current RAILS_EN...
rake db:environment:set                 # Set the environment value for the database
rake db:fixtures:load                   # Loads fixtures into the current environment's database
rake db:migrate                         # Migrate the database (options: VERSION=x, VERBOSE=false, SCOPE=blog)
rake db:migrate:status                  # Display status of migrations
rake db:rollback                        # Rolls the schema back to the previous version (specify steps w/ STEP=n)
rake db:schema:cache:clear              # Clears a db/schema_cache.yml file
rake db:schema:cache:dump               # Creates a db/schema_cache.yml file
rake db:schema:dump                     # Creates a db/schema.rb file that is portable against any DB supported by Active Record
rake db:schema:load                     # Loads a schema.rb file into the database
rake db:seed                            # Loads the seed data from db/seeds.rb
rake db:setup                           # Creates the database, loads the schema, and initializes with the seed data (use db:r...
rake db:structure:dump                  # Dumps the database structure to db/structure.sql
rake db:structure:load                  # Recreates the databases from the structure.sql file
rake db:version                         # Retrieves the current schema version number
rake dev:cache                          # Toggle development mode caching on/off
rake initializers                       # Print out all defined initializers in the order they are invoked by Rails
rake log:clear                          # Truncates all/specified *.log files in log/ to zero bytes (specify which logs with L...
rake middleware                         # Prints out your Rack middleware stack
rake notes                              # Enumerate all annotations (use notes:optimize, :fixme, :todo for focus)
rake notes:custom                       # Enumerate a custom annotation, specify with ANNOTATION=CUSTOM
rake restart                            # Restart app by touching tmp/restart.txt
rake routes                             # Print out all defined routes in match order, with names
rake secret                             # Generate a cryptographically secure secret key (this is typically used to generate a...
rake stats                              # Report code statistics (KLOCs, etc) from the application or engine
rake task_sample:sample                 # 実行処理の説明
rake test                               # Runs all tests in test folder except system ones
rake test:db                            # Run tests quickly, but also reset db
rake test:system                        # Run system tests only
rake time:zones[country_or_offset]      # List all time zones, list by two-letter country code (`rails time:zones[US]`), or li...
rake tmp:clear                          # Clear cache, socket and screenshot files from tmp/ (narrow w/ tmp:cache:clear, tmp:s...
rake tmp:create                         # Creates tmp directories for cache, sockets, and pids
rake yarn:install                       # Install all JavaScript dependencies as specified via Yarn

確かにdb:migrateとかありますね。
db:migrateのタスクの中身見てみようとしたけど、パット見ファイルの場所が見つからなかったので、またの機会にします。

wheneverを使用

whenever Gemfileに

gem 'whenever', require: false

を追加して、

$ bundle install
$ be wheneverize .
[add] writing `./config/schedule.rb'
[done] wheneverized!

config/schedule.rbを開いて

set :output, "log/development.log"
every 1.minute do
    rake "task_sample:sample"
end

と書いて、cronを登録する

# 登録します
$ bundle exec whenever --update-crontab

#これで確認できます
$ be whenever
* * * * * /bin/bash -l -c 'cd /Users/my0shym/hogeApp && RAILS_ENV=production bundle exec rake task_sample:sample --silent >> log/development.log 2>&1'

$ be rails sしておいて、別タブで$ tail -f log/development.logで確認する。
すると、見事Hello Worldが表示されました〜パチパチ

rakeタスクからDBとかにアクセスしたいときは

task :hoge => :environment do

が必要らしい。
と、ここでコロンとアローの使い方がうまく整理でいていないことが発覚したので、今度やる。