Scheduler Service

スケジューラサービス

The Scheduler is modeled after Unix Cron. The Scheduler runs as a background process that executes timed scheduled tasks independently of HTTP requests. Tasks are stored in the database in the TURBINE_SCHEDULED_JOB table and once entered in the database are loaded automatically when Turbine initializes.

スケジューラはUnix Cronを模範にしています。 スケジューラはバックグラウンドプロセスとして実行され、 HTTPリクエストとは独立したスケジュールされたタスク実行します。 タスクはデータベースのTURBINE_SCHEDULED_JOBテーブルに格納されており、 データベースに格納されているものはTurbineの初期化時に自動的にロードされます。

For the Scheduler to load classes that extend the ScheduledJob Class, the scheduler needs to be enabled via the TurbineResources.properties file, where the directive scheduler.enabled needs to be set to true.

スケジューラがScheduledJobクラスを継承したクラスをロードするためには、 TurbineResources.propertiesファイルのscheduler.enabledディレクティブをtrueに設定し、 スケジューラを有効としておく必要があります。

Configuration

設定

  # -------------------------------------------------------------------
  #
  #  S E R V I C E S
  #
  # -------------------------------------------------------------------

  # Classes for Turbine Services should be defined here.
  # Format: services.[name].classname=[implementing class]
  #
  # To specify properties of a service use the following syntax:
  # service.[name].[property]=[value]

  # Turbineのサービスのためのクラス群はここに定義します。
  # フォーマット: services.[name].classname=[implementing class]
  #
  # サービスのプロパティを設定するには、以下の書式を使用します:
  # service.[name].[property]=[value]

  services.SchedulerService.classname=org.apache.fulcrum.schedule.TurbineSchedulerService
  .
  .
  .
  # -------------------------------------------------------------------
  #
  #  S C H E D U L E R  S E R V I C E
  #
  # -------------------------------------------------------------------
  #

  # Set enabled to true to start the scheduler.
  #
  # Default = false
  #

  # スケジューラを起動するためにtrueに設定します。
  #
  # デフォルト = false
  #
  scheduler.enabled=true

  

Usage

使用方法

To create an object that takes advantage of the Schedule Service, the task to be executed will need to be embedded in the run() method of an object which extends the ScheduledJob Class. For instance:

スケジューラサービスを利用するオブジェクトを作成します。 実行されるタスクはScheduledJobクラスを継承し、run()メソッドを実装する必要があります。 例:


  package com.mycompany.modules.scheduledjobs;

  //JDK
  import java.util.Date;

  //Turbine
  import org.apache.fulcrum.schedule.ScheduledJob;
  import org.apache.fulcrum.schedule.JobEntry;
  import org.apache.turbine.util.Log;

  public class SimpleScheduledTask extends ScheduledJob
  {
      private int taskcount = 0;

      /**

       * Constructor

       * コンストラクタ
       */
      public SimpleScheduledTask()
      {

          //do Task initialization here

          //ここではタスクの初期化を行う
      }

      /**

       * Run the Jobentry from the scheduler queue.
       * From ScheduledJob.
       *
       * @param job The job to run.

       * スケジューラキューのJobEntryを実行する。
       * ScheduledJobで定義されているメソッド。
       *
       * @param job 実行するジョブ
       */
      public void run( JobEntry job ) throws Exception
      {
          Log.note("Scheduled job " + job.getId() + " : " +
              "task: " + job.getTask() + " ran @: " +
                  new Date(System.currentTimeMillis()).toString() +
                      " taskcount " + taskcount);


          //iterate the task counter

          //タスクカウンタをカウントアップする
          taskcount++;
      }
  }

  

The SimpleScheduledTask object makes an entry into the turbine.log each time the Task is run by the Schedule Service. The JobEntry object carries the information the Service uses to determine the frequency of the Task. Note that the object is in the com.mycompany.modules. This assumes that the package com.mycompany.modules is in the Turbine module path, which is in the module.packages directive in the TurbineResources.properties. The ScheduledJobLoader object loads the Task upon Turbine initilization also searches for a scheduledjobs package which contains the Task object.

SimpleScheduledTaskオブジェクトは、スケジュールサービスによってタスクが実行されるたびに、turbine.logへエントリを作成します。 JobEntryオブジェクトはサービスがタスクの周期を決定するために使用する情報を持っています。 このオブジェクトがcom.mycompany.modulesパッケージにあることに注意してください。 これはTurbine.propertiesのmodule.packagesディレクティブで指定されるTurbineのモジュールパスがcom.mycompany.modulesにあると仮定しています。 ScheduledJobLoaderオブジェクトはTuibineの初期化時にタスクのオブジェクト含むscheduledjobsパッケージを探し、タスクをロードします。

Control of the time between, or to, execution of the Task, is controlled by the JobEntry object. The JobEntry serves as a wrapper for the scheduled task. The constructor is as follows:

時間間隔のコントロール、タスクの実行はJobEntryオブジェクトによってコントロールされます。 JobEntryはスケジュールするタスクのラッパとして機能します。 コンストラクタは以下のようになっています:


  public JobEntry(int sec, int min, int hour,
                  int wd, int day_mo, String task)
      throws Exception

  

The granularity of the Task's next execution can be controlled to the level of seconds. In the above constructor, sec represents the seconds with a valid range of 0-59, min represents the minutes with a valid range of 0-59, hour represents the hours with a valid range of 0-23, wd is the day of the week with a valid range of 1-7, day_mo is the day of the month with a valid range of 1-31 and task is the name of the object. The JobEntry constructor allows for the Task to be run at a certain point in time. For example:

タスクの次の実行単位は秒レベルでコントロールすることができます。 上記のコンストラクタでは、secが0-59の有効範囲を持ち、これは秒を表します。 minは0-59の有効範囲を持ち、これは分を表します。 hourは0-23の有効範囲を持ち、これは時を表します。 wdは1-7の有効範囲を持ち、週の何番目の日かを表します。 day_moは1-31の有効範囲を持ち、月の何番目の日かを表します。 そしてtaskは、オブジェクトの名称です。 JobEntryのコンストラクタはタスクが実行されるタイミングを受け取るのです。 例:


  JobEntry je = new JobEntry(0,25,-1,-1,-1,"SimpleScheduledTask");


  o run every 25 minutes.

  o 25分毎に実行

  JobEntry je = new JobEntry(0,0,8,-1,15,"SimpleScheduledTask");


  o run at 8:00am on the 15th of the month every month.

  o 毎月15日の午前8時に実行

  

The Schedule Service will only execute Tasks at Turbine Initialization that are present in the Database. To add a Task to the Database we need to set up an Action class that can be accessed from a template with:

スケジュールサービスはデータベースに格納されているTurbineの初期化情報のタスクを実行するだけです。 タスクをデータベースに追加するには、このようなテンプレートからアクセスできるActionクラスを作成する必要があります:


  $page.SetTitle("SimpleScheduleTask Starter Page")

  Set Values for SimpleScheduleTask and then start it for the first time.
  <br/>

  <form>
  <input type="hidden" name="action" value="SchedulerStart" />
  <input type="text" name="second" size="20" /> : seconds (0-59)<br />
  <input type="text" name="minute" size="20" /> : minutes (0-59)<br />
  <input type="text" name="hour" size="20" /> : hours (0-23)<br />
  <input type="text" name="weekday" size="20" /> : Day of the Week (1-7)<br />
  <input type="text" name="day_of_month" size="20" /> Day of the Month (1-31)<br />
  <input type="text" name="task" value="SimpleSchedulerTask" /> : The Task being scheduled. <br />
  <input type="text" name="email" /> : Email<br />
  </form>

  

and the appropriate Action class:

それと、Actionクラス:


  package com.mycompany.modules.actions;

  //Turbine
  import org.apache.turbine.util.RunData;
  import org.apache.fulcrum.schedule.JobEntry;
  import org.apache.fulcrum.schedule.ScheduleService;
  import org.apache.turbine.modules.actions.VelocityAction;

  public class SchedulerStart extends VelocityAction
  {

       public void doPerform(RunData data) throws Exception
       {
          ParameterParser params = data.getParameters();

          int second = params.getInt("second",-1);
          int minute = params.getInt("minute",-1);
          int hour = params.getInt("hour",-1);
          int weekday = params.getInt("weekday",-1);
          int dom = params.getInt("day_of_month",-1);
          String task = params.getString("task","");
          String email = params.getString("email","");

          try
          {

              //access the service singleton

              //サービスシングルトンへのアクセス
              ScheduleService ss = (ScheduleService)TurbineServices
                  .getInstance().getService(ScheduleService.SERVICE_NAME);


              //create a new JobEntry with the time constraints from
              //the template as the arguments

              //テンプレートからの時間指定を引数として新しいJobEntryを作成する
              JobEntry je =  new JobEntry(second,minute,hour,weekday,dom,task);


              //set the email for notification

              //通知のためのemailをセットする
              je.setEmail(email);


              //add the job to the queue

              //キューにジョブを追加する
              ss.addJob(je);


              //set the Message

              //メッセージをセットする
              data.setMessage("Task " + task + "started successfully");
          }
          catch (Exception e)
          {

              //set the Message

              //メッセージをセットする
              data.setMessage("Task " + task + " failed to start!");
          }

          setTemplate(schedule,SchedulerStatus.vm);
       }
  }

  

The SchedulerStart Action class initializes the Scheduler for that Task. The TurbineSchedulerService object exposes other methods that allow the Scheduler process to be monitored, such as getJob(int oid), removeJob(JobEntry je), updateJob(JobEntry je), listJobs(). As well as methods which allow the Scheduler thread to be accessed.

SchedulerStart Actionクラスはこのタスクのスケジューラを初期化を行います。 TurbineSchedulerServiceオブジェクトはスケジューラの処理をモニタリングすることを可能とするgetJob(int oid), removeJob(JobEntry je), updateJob(JobEntry je), listJobs()のような他のメソッドを公開しています。 同様に、これらのメソッドはスケジューラスレッドからアクセスされます。

The Scheduler Service uses a seperate thread for each Task it runs to ensure that every job runs on time. It's the programmer's responsibility to ensure that proper precautions to handle issues such as synchronization and long running jobs. As always, check through the relevant Javadocs and source code for more details on the Scheduler Service.

スケジューラサービスは、すべてのジョブが時間通りに走ることを保証するために、実行するタスクごとにスレッドを使用します。 同期や、時間のかかるジョブなどの問題を処理し、適切な予防策を保証するのはプログラマの責任です。 いつもと同じように、スケジューラサービスについてのより詳細については関連するJavadocおよびソースコードを調べてください。

Properties Based Scheduler

プロパティベースのスケジューラ

Service for a cron like scheduler that uses the TurbineResources.properties file instead of the database. The methods that operate on jobs ( get,add,update,remove ) only operate on the queue in memory and changes are not reflected to the properties file which was used to initilize the jobs. An example is given below. The job names are the class names that extend ScheduledJob.

データベースの代わりにTurbineResources.propertiesファイルを使用するcronに似たスケジューラサービスもあります。 ジョブの操作 ( get,add,update,remove ) メソッドは、メモリ内のキュー上でのみ操作できるものであり、ジョブを初期化するプロパティファイルに変更は反映されません。 例を以下に挙げます。 ジョブの名前はScheduledJobを継承したクラスの名前です。

Here is a sample configuration that you might add to your Fulcrum.properties to use the non persistent scheduler:

これはFulcrum.propertiesに追加するような、永続化されないスケジューラを使用する設定のサンプルです:


  services.SchedulerService.scheduler.jobs=scheduledJobName,scheduledJobName2

  services.SchedulerService.scheduler.job.scheduledJobName.ID=1
  services.SchedulerService.scheduler.job.scheduledJobName.SECOND=-1
  services.SchedulerService.scheduler.job.scheduledJobName.MINUTE=-1
  services.SchedulerService.scheduler.job.scheduledJobName.HOUR=7
  services.SchedulerService.scheduler.job.scheduledJobName.WEEKDAY=-1
  services.SchedulerService.scheduler.job.scheduledJobName.DAY_OF_MONTH=-1

  services.SchedulerService.scheduler.job.scheduledJobName2.ID=1
  services.SchedulerService.scheduler.job.scheduledJobName2.SECOND=-1
  services.SchedulerService.scheduler.job.scheduledJobName2.MINUTE=-1
  services.SchedulerService.scheduler.job.scheduledJobName2.HOUR=7
  services.SchedulerService.scheduler.job.scheduledJobName2.WEEKDAY=-1
  services.SchedulerService.scheduler.job.scheduledJobName2.DAY_OF_MONTH=-1