(O+P)ut

アウトプット



(O+P)ut

エンジニアのアウトプット

【Cygwin】cronをインストールして毎分コマンドを実行する

スポンサーリンク

やりたいこと

Windows環境にてUNIXライクにcronを動かす。

環境情報
$ bash --version
GNU bash, バージョン 4.4.12(3)-release (x86_64-unknown-cygwin)

やり方

管理者権限でCygwinを開いて同作業を実施していきます。

以下でcron関係のコマンド群をインストールし、

$ apt-cyg install cron

cronコマンドが/usr/sbin/cronが配置されるので以下でサービスとして登録します。

$ cygrunsrv -I cron -p /usr/sbin/cron -a -n

確認として以下で登録状況&ステータスを表示できます。

$ cygrunsrv -L
cron
$  cygrunsrv -Q cron
Service             : cron
Current State       : Stopped
Command             : /usr/sbin/cron -n

以下でcronサービスをRunning状態にします。

$  cygrunsrv -S cron

このままでは「(CRON) error (can't switch user context)」というエラーでcronに登録したコマンドが打てないので、以下コマンドで仮パスワード(空でもOK)を登録します。

$ passwd -R
This functionality stores a password in the registry for usage by services
which need to change the user context and require network access.  Typical
applications are interactive remote logons using sshd, cron task, etc.
This password will always tried first when any privileged application is
about to switch the user context.

Note that storing even obfuscated passwords in the registry is not overly
secure.  Use this feature only if the machine is adequately locked down.
Don't use this feature if you don't need network access within a remote
session.

You can delete the stored password by specifying an empty password.

Enter your current password:
Re-enter your current password:

最後にcron-configコマンドで再インストールすれば「The cron daemon is now running...」という文言が出て

$ cron-config
The cron daemon can run as a service or as a job. The latter is not recommended.
Cron is already installed as a service under account LocalSystem.
Do you want to remove or reinstall it? (yes/no) yes
OK. The cron service was removed.

Do you want to install the cron daemon as a service? (yes/no) no
Running cron_diagnose ...
... no problem found.

Do you want to start the cron daemon as a job now? (yes/no) yes
WARNING: The cron daemon will stop when you log off.
         To avoid that, launch cron as a service (using cygrunsrv).
OK. The cron daemon is now running...

crontabに記載した通りcron処理が行われます。尚、Windowsを再起動させるとcronサービスは停止します。

以下は毎分dateコマンドを打つ例。

* * * * * date >> /tmp/hoge.txt

以下、補足です。

補足

croneventsコマンドを打てばcron周りのログ情報が確認できます。
例えばcrontab -lで表示したり-eで編集すると以下のような出力になります。

$ /usr/bin/cronevents
crontab: PID 1959: xx LIST xx
crontab: PID 1960: xx BEGIN EDIT xx
crontab: PID 1960: xx END EDIT xx

cygrunsrvでスタートした時点で以下のようにログ上は動き出しますが

[SYSTEM] /usr/sbin/cron: PID 2057: (CRON) STARTUP (V5.0)
[SYSTEM] cron: PID 2056: `cron' service started

passwd -Rやcronconfigを終えないと、定期実行しようとしても以下のようにエラーとなります。

[SYSTEM] /usr/sbin/cron: PID 2060: XX CMD (date >> /tmp/hoge.txt)
[SYSTEM] /usr/sbin/cron: PID 2060: (CRON) error (can't switch user context)

以上、ご参考になれば幸いです。