VPSでCronとAnacronを使用して日常的なタスクをスケジュールする方法

提供:Dev Guides
移動先:案内検索

cronとは何ですか?

Cronは、事前設定された時間に実行するタスクを割り当てることができるスケジューリングユーティリティです。 基本的なツールであるcronを使用して、定期的に発生する必要のあるシステム上のほぼすべてのものを自動化できます。

毎時または毎日実行する必要のあるタスクと、年に1〜2回実行する必要のある大規模なルーチンの管理にも同様に精通しているcronは、システム管理者にとって不可欠なツールです。

このガイドでは、コマンドラインからcronを使用する方法と、その構成ファイルを読み取る方法について説明します。 また、サーバーの電源がオフになっている場合でもタスクを確実に実行するために使用できるツールであるanacronについても説明します。

Ubuntu 12.04 VPSを使用しますが、最新のLinuxディストリビューションも同様に動作するはずです。

cronのしくみ

Cronは起動時に起動され、デーモンとしてバックグラウンドで実行されます。 これは、ユーザーの操作なしで実行され、特定のイベントが発生するのを待って、いつ実行するかを決定することを意味します。

cronの場合、これらのイベントは特定の瞬間です。 Cronはバックグラウンドで実行され、構成ファイルを1分ごとにチェックして、イベントがその分に実行されるようにスケジュールされているかどうかを確認します。

イベントがスケジュールされている場合、cronは事前に設定されたコマンドを実行してから、さらに1分間バックグラウンドに戻ります。 イベントがスケジュールされていない場合は、60秒待機してから再度チェックします。

この分単位のスケジューリングにより、非常に柔軟で構成可能です。 ディストリビューションをインストールすると、cronはさまざまなタスクを実行するようにすでに構成されています。

crontabの読み方

Cronは、それぞれが「crontab」と呼ばれる一連のファイルを読み取ることにより、どのコマンドをいつ実行するかを決定します。 「/etc/ crontab」を見ると、システム全体のcrontabを確認できます。

less /etc/crontab
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# m h dom mon dow user  command
17 *    * * *   root    cd / && run-parts --report /etc/cron.hourly
25 6    * * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
47 6    * * 7   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
52 6    1 * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )

これはシステムのcrontabであり、ほとんどの場合編集しないでください。 ほとんどの場合、独自のcrontabを使用することをお勧めします。 システムファイルはアップデートで置き換えられる可能性があり、変更は失われます。

このファイルには、理解する必要のある興味深い部分がいくつかあります。

最初の2行は、リストされているコマンドを実行するシェルと、プログラムをチェックするためのパスを指定します。

ファイルの残りの部分は、実際のコマンドとスケジューリングを指定します。 このリストの行はそれぞれ、テーブル内のレコードまたは行を表します。 「crontab」の「tab」はテーブルを表します。 各テーブルセルは、スペースまたはタブで区切られた列で表されます。

表の上のコメント行は、各列が何を表しているかについてのヒントを示しています。

# m h dom mon dow user  command

cronを使用した時間と分のスケジューリング

最初の列は、コマンドを実行する時間の分(0〜59)です。 2番目の列は、実行する必要がある0〜23の時間です。 アスタリスク(*)は「可能な限りの値」を意味し、ワイルドカードとして使用されます。

これらの最初の2つの列を組み合わせることで、コマンドの時間値を取得できます。 たとえば、表の2行目は、分列に25、時間列に6があります。

25 6    * * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )

これは、2番目のラインが午前6時25分に実行される必要があることを意味します。

同様に、最初の行は、コマンドが1時間ごとに実行され、17分が1時間経過したことを意味します。

17 *    * * *   root    cd / && run-parts --report /etc/cron.hourly

したがって、午前1時17分、午前2時17分、午前3時17分などに実行されます。

cronによる日数のスケジューリング

3番目、4番目、および5番目の列は、コマンドを実行する日を決定します。 3番目の列は、月の日1〜31を指定します(すべての月の日数が同じであるとは限らないため、月の後半にスケジュールする場合は注意してください)。

4番目の列は、コマンドを実行する1〜12の月を指定し、5番目の列は、コマンドを実行する曜日を指定するために予約されています。0と7はどちらも日曜日を意味します。 この最後の1つでは、月単位ではなく週単位でスケジュールを設定できます。

曜日と曜日の両方の列にワイルドカードではない値が含まれている場合、いずれかの列が一致するとコマンドが実行されます。

曜日と月は、名前の最初の3文字で指定することもできます。 ハイフン(-)を使用して範囲を使用し、コンマ(、)を使用して複数の値を選択することもできます。

/と数値を使用して値を追跡することにより、間隔を指定することもできます。 たとえば、1時間おきにコマンドを実行するには、「時間」列に「*/2」を配置します。

crontabを見ると、3番目のレコードが毎週日曜日の午前6時47分に実行されていることがわかります。

47 6    * * 7   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )

4番目のレコードは、月の1日の午前6時52分に実行されます。

52 6    1 * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )

時間ショートカットを使用したスケジュール

単純な要件がある場合は、各レコードの最初の5列を名前付きショートカットに置き換えることができます。 これらの構文は、「@」の後に名前付き間隔が続きます。

たとえば、5列の構成を作成する代わりに、「@ weekly」を指定することで、毎週実行されるようにスケジュールを設定できます。 その他の選択肢は、「@ yearly」、「@ monthly」、「@ daily」、および「@hourly」です。

cronが開始されるとすぐに実行される「@reboot」と呼ばれる特別なショートカットもあります。 これは通常、システムの起動時にのみ発生します。そのため、「cron-restart」などではなく「reboot」と呼ばれます。

これらのショートカットは、いつ実行されるかをきめ細かく制御できないことに注意してください。 また、これらはすべて、一致する時間の最初の可能な瞬間に実行されるように構成されています。

たとえば、「@monthly」は月の最初の深夜に実行されます。 これにより、すべてが同時に実行される場合、一度に実行するようにスケジュールされた多くのコマンドが発生する可能性があります。 従来のスケジューリング構文のように、これらのイベントをずらすことはできません。

Cronを使用したコマンドとユーザーの指定

次の列には、スケジュールされたコマンドの実際の実行が含まれます。

私たちが見ているシステムcrontabにのみ存在する6番目の列は、コマンドを実行するユーザーを示しています。

最後の列は、実行する必要のある実際のコマンドを指定します。 コマンドにはパーセント記号(%)を含めることができます。これは、最初のパーセント記号以外のすべてが標準入力としてコマンドに渡されることを意味します。

すべてのレコードは、改行文字で終了する必要があります。 これはほとんどのエントリでは問題になりませんが、最後のエントリの後に空白行があることを確認してください。そうしないと、コマンドが正しく実行されません。

run-partsとcronディレクトリの使用

システムのcrontabで指定されているコマンドを見ると、後で説明する「anacron」と「run-parts」についての言及があります。

run-partsコマンドは、指定されたディレクトリ内にあるすべての実行可能ファイルを実行する単純なコマンドです。 複数のスクリプトを1つの場所に配置することで、指定した時間に複数のスクリプトを実行できるため、cronで広く使用されています。

これには、crontabをクリーンでシンプルに保つことができ、crontabを調整する代わりに、スクリプトを適切なディレクトリに配置またはリンクするだけでスクリプトを追加できるという利点があります。

デフォルトでは、ほとんどのディストリビューションは間隔ごとにフォルダーを設定し、その間隔で実行するスクリプトまたはスクリプトへのリンクを配置します。

たとえば、Ubuntuには、「cron.daily」、「cron.hourly」、「cron.monthly」、および「cron.weekly」という名前のフォルダーがあります。 これらのフォルダの中には、適切なスクリプトがあります。

ユーザー固有のcronタブの使用

cronの構文を理解したので、これを使用して、自分のユーザーのスケジュールされたタスクを作成できます。 これは「crontab」コマンドで実行できます。

crontabのコマンドはユーザー権限で実行されるため、「user」列はユーザー固有のcrontabには存在しません。

現在のcrontabを表示するには、次のように入力します。

crontab -l

特に手作業で作成しない限り、おそらく持っていないでしょう。 crontabがある場合は、編集する前に現在のコピーをバックアップして、行った変更を元に戻すことができるようにすることをお勧めします。

バックアップをホームディレクトリの「cron.bak」というファイルに保存するには、次のコマンドを実行します。

crontab -l > ~/cron.back

crontabを編集するには、次のように入力します。

crontab -e
no crontab for demouser - using an empty one

Select an editor.  To change later, run 'select-editor'.
  1. /bin/nano        
You might be given a selection prompt similar to the one above your first time using this command.  Select the editor you prefer to continue.
You will be dropped into a commented file that you can edit to create your own rules.
As a nonsensical example, if we wanted to echo the date into a file every 15 minutes every Wednesday, we could place this line into the file:
*/15 * * * 3 echo "$(date)" >> /home/demouser/file

We can then save the file and now, when we run "crontab -l", we should see the rule we just created:

crontab -l
. . .
. . .
*/15 * * * 3 echo "$(date)" >> /home/demouser/file

If you need to edit the crontab of a specific user, you can also add the "-u username" option. You will only be able to do this as root or with an account with administrative privileges.

For instance, if you would like to add something to the "root" crontab, you could issue:

sudo crontab -u root -e

Using Anacron with Cron

One of cron's biggest weaknesses is that it assumes that your server or computer is always on. If your machine is off and you have a task scheduled during that time, the task will never run.

This is a serious problem with systems that cannot be guaranteed to be on at any given time. Due to this scenario, a tool called "anacron" was developed. Anacron stands for anachronistic, and it is used compensate for this problem with cron.

Anacron uses parameters that are not as detailed as cron's options. The smallest increment that anacron understands is days. This means that anacron should be used to complement cron, not to replace it.

Anacron's advantage is that it uses time-stamped files to find out when the last time its commands were executed. This means, if a task is scheduled to be run daily and the computer was turned off during that time, when anacron is run, it can see that the task was last run more than 24 hours ago and execute the task correctly.

The anacron utility has a scheduling table just like cron does. It is appropriately named "anacrontab" and is located in the "/etc" directory as well. Let's see how it is formatted:

less /etc/anacrontab
# /etc/anacrontab: configuration file for anacron

# See anacron(8) and anacrontab(5) for details.

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# These replace cron's entries
1       5       cron.daily       nice run-parts --report /etc/cron.daily
7       10      cron.weekly      nice run-parts --report /etc/cron.weekly
@monthly        15      cron.monthly nice run-parts --report /etc/cron.monthly

We can see that it follows a similar format to the "crontab" files, but there are fewer columns and some noticeable differences.

The first column specifies how often the command should be run. It is given as an interval in days. A value of "1" will run every day, while a value of "3" will run every three days.

The second column is the delay to use before executing the commands. Anacron is not a daemon. It is run explicitly at one time. This field allows you to stagger execution so that not every task is running at the same time.

For example, the first line runs every day, five minutes after anacron is called:

1       5       cron.daily       nice run-parts --report /etc/cron.daily

The following line is run weekly (every 7 days), ten minutes after anacron is called:

7       10      cron.weekly      nice run-parts --report /etc/cron.weekly

The third column contains the name that the job will be known as in the anacron's messages and log files. The fourth field is the actual command that is run.

You can see that anacron is set to run some of the same scripts that are run by cron. Distributions handle this clash differently, by creating a preference for either cron or anacron and making the other program not execute the rule.

For instance, on Ubuntu, the "/etc/crontab" tests if anacron is available on the system, and only executes the scripts in the cron.* directories with cron if anacron is not found.

Other distributions have cron update the anacron's time-stamps every time it runs the contents of these directories, so that anacron does not execute when it is called.

Conclusion

Both cron and anacron are useful tools for when you need to automate processes. Understanding how to leverage their strengths and work around their weaknesses will allow you to utilize them easily and effectively.

Although the configuration syntax may be confusing at first, these tools will save you time in the long run and usually do not have to be adjusted often once you have a good working schedule.