2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

C#でWindowsサービスを作る(6)

Posted at

概要

前回の記事C#でWindows Serviceを作る(5)の続き。
タイマー処理の実装を行った際の備忘録。

環境

Windows 10
Visual Studio 2019 Community
⇒前回は2017でしたが、今回から諸般の事情で2019にしてます。すみません・・・。

手順

サービスでよくある処理は、定周期で何かを実行することだと思います。

ServiceBaseクラスの派生クラス(デフォルトだとService1.csというファイル。私のプロジェクトではServiceTest.cs)を開きます。

まず、以下のusingステートメントを追加して、タイマーコンポーネントを使用できるようにします。

using System.Timers;

つづいてタイマーコンポーネントの生成、設定をしていきます。
Intervalで、周期を指定します。
周期はミリ秒単位で指定できます。
⇒例えば分単位で実行したい場合は、60000を指定します。

Elapsedに、指定した周期が経過した際に実行されるイベント処理関数(ここではOnTimerという関数)を登録します。

Start関数を呼び出すと、タイマーが起動します。

    // タイマー処理
    CheckTimer = new Timer();
    CheckTimer.Interval = 60000; // 1分(60秒)
    CheckTimer.Elapsed += new ElapsedEventHandler(this.OnTimer);
    CheckTimer.Start();

ここではOnTimer関数内に、周期実行したい処理を記載します。

    protected void OnTimer(object sender, EventArgs e)
    {
        // 定周期処理
    }

周期実行を止めたい場合は、Stop関数を呼び出します。

    CheckTimer.Stop();

※Enabledをfalseに設定することでも、タイマー処理を停止できるようですね。
https://docs.microsoft.com/en-us/dotnet/api/system.timers.timer.stop?view=net-6.0#remarks

参考

チュートリアル: Windows サービス アプリを作成する

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?