テンプレートテスト
ブログの説明
ブログの説明2
menu
keyboard_arrow_up
Top
search
close
home
ホーム
computer
PC一般
construction
開発環境・ツール
code
プログラミング
home
ホーム
computer
PC一般
construction
開発環境・ツール
code
プログラミング
Home
›
ASP.NET Core
›
ASP.NET Core (.NET Core) でバックグランドタスクを起動する
2020/01/16
ASP.NET Core (.NET Core) でバックグランドタスクを起動する
update
event_note
label
.NET Core
label
ASP.NET Core
ASP.NET Core (.NET Core) において、アプリケーションの起動に合わせてバックグラウンドタスクを起動させる方法です。
- https://docs.microsoft.com/ja-jp/dotnet/standard/microservices-architecture/multi-container-microservice-net-applications/background-tasks-with-ihostedservice ## 環境 - Visual Studio 2017 - .NET Core 2.2 ## 概要 `IHostedService` を実装したサービスクラスを作成します。 `IHostedService` を使用するには、Nuget で `Microsoft.Extensions.Hosting` を追加する必要があります。 サービスクラスを `IHostedService` として DI コンテナに登録すると、Host が自動でバックグラウンドタスクとして実行してくれるようです。 Host については、作成するアプリケーションによって以下の2種類があるようです。 - ASP.NET Core で使用する Web ホスト (IWebHostBuilder) - ASP.NET Core 以外で使用する汎用ホスト (HostBuilder) ASP.NET Core の場合、テンプレートからプロジェクトを作成した段階で Web ホストが使用されている状態なので、特に意識はしなくても大丈夫そうですが、コンソールアプリなどの場合は汎用ホストを使用するように実装する必要があります。 ## ASP.NET Core の場合(Web ホスト) ASP.NET Core のほうが話が簡単なので、先に ASP.NET Core で説明します。 コンソールアプリなどでは必要となる汎用ホストについては後述します。 ### IHostedService の実装 [公式のドキュメント](https://docs.microsoft.com/ja-jp/dotnet/architecture/microservices/multi-container-microservice-net-applications/background-tasks-with-ihostedservice)に詳しく書いてありますが、ほとんどのバックグラウンドタスクではタスクの開始や終了といった動作は同じであるため、`IHostedService` を実装した抽象クラスを作成しておくと良いようです。 サンプルコードをそのまま引用します。 ```cs // Copyright (c) .NET Foundation. Licensed under the Apache License, Version 2.0. ///
/// Base class for implementing a long running
. ///
public abstract class BackgroundService : IHostedService, IDisposable { private Task _executingTask; private readonly CancellationTokenSource _stoppingCts = new CancellationTokenSource(); protected abstract Task ExecuteAsync(CancellationToken stoppingToken); public virtual Task StartAsync(CancellationToken cancellationToken) { // Store the task we're executing _executingTask = ExecuteAsync(_stoppingCts.Token); // If the task is completed then return it, // this will bubble cancellation and failure to the caller if (_executingTask.IsCompleted) { return _executingTask; } // Otherwise it's running return Task.CompletedTask; } public virtual async Task StopAsync(CancellationToken cancellationToken) { // Stop called without start if (_executingTask == null) { return; } try { // Signal cancellation to the executing method _stoppingCts.Cancel(); } finally { // Wait until the task completes or the stop token triggers await Task.WhenAny(_executingTask, Task.Delay(Timeout.Infinite, cancellationToken)); } } public virtual void Dispose() { _stoppingCts.Cancel(); } } ``` そして、この抽象クラスを継承してバックグランドで動かしたいサービスクラスを定義します。 コードの概要は以下です。 ```cs public class SampleService : BackgroundService { public SampleService() { // コンストラクタへの引数は自動で DI される } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { // ここに常駐処理を定義する } } ``` `ExecuteAsync` 内では `while` で常駐処理を定義し、タスクの終了のチェックなども行います。 以下、[公式のドキュメント](https://docs.microsoft.com/ja-jp/dotnet/architecture/microservices/multi-container-microservice-net-applications/background-tasks-with-ihostedservice)のサンプルを引用します。 ```cs public class GracePeriodManagerService : BackgroundService { private readonly ILogger
_logger; private readonly OrderingBackgroundSettings _settings; private readonly IEventBus _eventBus; public GracePeriodManagerService(IOptions
settings, IEventBus eventBus, ILogger
logger) { //Constructor’s parameters validations... } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { _logger.LogDebug($"GracePeriodManagerService is starting."); stoppingToken.Register(() => _logger.LogDebug($" GracePeriod background task is stopping.")); while (!stoppingToken.IsCancellationRequested) { _logger.LogDebug($"GracePeriod task doing background work."); // This eShopOnContainers method is querying a database table // and publishing events into the Event Bus (RabbitMQ / ServiceBus) CheckConfirmedGracePeriodOrders(); await Task.Delay(_settings.CheckUpdateTime, stoppingToken); } _logger.LogDebug($"GracePeriod background task is stopping."); } .../... } ``` ### DI コンテナへのサービスの追加 `Startup.cs` の `ConfigureServices` メソッドで、サービスクラスを DI コンテナに登録します。 `IHostedService` を実装したクラスを `AddHostedService` で登録していきます。 (`AddSingleton` でも可) ```cs public void ConfigureServices(IServiceCollection services) { // ... services.AddHostedService
(); services.AddHostedService
(); // または services.AddSingleton
(); services.AddSingleton
(); } ``` ## 汎用ホスト ASP.NET Core 以外(例えばコンソールアプリなど)では汎用ホストを作成する必要があります。 基本的なコードは以下です。 ```cs public static async Task Main(string[] args) { var host = new HostBuilder() .Build(); await host.RunAsync(); } ``` ### IHostedService の実装 前述の ASP.NET Core と同様のため省略します。 ### DI コンテナへのサービス追加 `IHostedService` を DI するためにも、DI コンテナにサービスを追加する必要があります。 `ConfigureServices` で行います。 ```cs var host = new HostBuilder() .ConfigureServices((hostContext, services) => { services.AddHostedService
(); services.AddHostedService
(); // または services.AddSingleton
(); services.AddSingleton
(); }) .Build(); await host.RunAsync(); ``` `ConfigureServices` の中身については ASP.NET Core と同じです。 他にもいろいろ設定可能ですが、ここでは DI コンテナしか関係ないので、省略します。 詳細は以下を参照してください。 - https://docs.microsoft.com/ja-jp/aspnet/core/fundamentals/host/generic-host
## 参考 URL - https://docs.microsoft.com/ja-jp/dotnet/standard/microservices-architecture/multi-container-microservice-net-applications/background-tasks-with-ihostedservice - https://docs.microsoft.com/ja-jp/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-2.2 - https://docs.microsoft.com/ja-jp/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-2.2
tweet
facebook
Pocket
B!
はてブ
LINE
chevron_left
chevron_right
Translate
Popular Posts
ASP.NET Core で AdminLTE を使用する
TortoiseGit でリモートリポジトリのタグを削除する
TortoiseGit でコミットメッセージを変更する
image
NO IMAGE
C# と C/C++ のライブラリを混在させる場合の構成
image
NO IMAGE
ASP.NET Core におけるフロントエンドのパッケージ管理
image
NO IMAGE
TortoiseGit でブランチ間の差分を見る
image
NO IMAGE
[C#] Dictionary の キーがタプルの場合に JSON へのシリアライズとデシリアライズを行う方法
image
NO IMAGE
ASP.NET Core (.NET Core) でバックグランドタスクを起動する
ASP.NET Core アプリケーションを外部に公開するための Windows ファイアウォールの設定
image
NO IMAGE
.NET アプリケーションを XCOPY 配置で配布する
Labels
.NET Core
31
.NET Framework
17
.NET Standard
2
AdminLTE
1
Apache
3
AppVeyor
2
AsciiDoc
3
ASP.NET Core
55
Atom
4
AWS
2
AWS Cloud9
4
blockdiag
1
Blogger
10
Bootstrap
3
C/C++
6
C#
106
CentOS
3
Chrome
1
Chronograf
3
Codecov
1
CSS
1
Docker
28
DokuWiki
4
Doxygen
1
draw.io
1
Electron.NET
2
Entity Framework Core
9
Excel
2
FFmpeg
2
Firefox
5
Git
12
GitBook
4
GitBucket
7
GitHub
7
GitLab
30
Go
1
Google
1
Google Cloud Platform
1
Grafana
5
HTML
5
IIS
8
InfluxDB
6
JavaScript
7
Jenkins
7
Linux
25
Log4View
1
MahApps.Metro
3
MaterialDesignInXamlToolkit
1
MVC
1
MVVM
6
NLog
3
Node.js
3
npm
1
OpenSSL
3
ownCloud
2
Pine Script
1
PlantUML
5
PowerShell
7
Prism
2
Python
11
Razor
3
Redmine
30
remark.js
2
rocketchat
4
Ruby
3
SignalR
1
Socket.IO
1
SonarQube
5
Sphinx
10
SQL Server
5
SQLite
1
t
1
TestLink
2
Tomcat
2
TortoiseGit
10
TortoiseSVN
2
Trading View
1
Travis CI
1
Ubuntu
13
Visual Studio
39
Visual Studio Code
9
Vue.js
8
Windows
56
Windows 10
4
Windows ADK
1
Windows API
2
Windows Embedded
4
wkhtmltopdf
2
Word
3
WPF
12
WSL
1
Xamarin
1
xUnit
5
アプリケーション
1
デザインパターン
1
テスト
3
バッチファイル
2
ぴよ
3
プログラミング
3
ライセンス
1
ラベル
3
ラベル1
2
英語
2
雑記
1
書籍
1
数学
1
正規表現
1
Blog Archive
►
2022
(1)
►
2月
(1)
►
2021
(24)
►
5月
(7)
►
4月
(8)
►
3月
(2)
►
2月
(2)
►
1月
(5)
▼
2020
(60)
►
12月
(1)
►
11月
(3)
►
10月
(3)
►
9月
(3)
►
8月
(3)
►
7月
(7)
►
6月
(7)
►
5月
(2)
►
4月
(6)
►
3月
(6)
►
2月
(7)
▼
1月
(12)
[JavaScript] 数値の変わった表記
[Python] インデックス付きのループ
ASP.NET Core (.NET Core) でバックグランドタスクを起動する
NuGet Server でプライベートリポジトリを構築する
GitLab の Admin / Runners で 500 エラーが表示される
[C#] 動的な JSON を扱う
[Python] 書式指定で変数を使う
[Python] 文字列の出力
VSCode での Python のデバッグ設定
VSCode で Python の import や from のエラーが消えない
Python で ta-lib をインストールする
Windows に Python をインストール
►
2019
(92)
►
12月
(13)
►
11月
(9)
►
10月
(3)
►
9月
(2)
►
8月
(3)
►
7月
(5)
►
6月
(11)
►
5月
(6)
►
4月
(17)
►
3月
(9)
►
2月
(6)
►
1月
(8)
►
2018
(100)
►
12月
(1)
►
11月
(11)
►
10月
(8)
►
9月
(6)
►
8月
(10)
►
7月
(10)
►
6月
(8)
►
5月
(9)
►
4月
(8)
►
3月
(14)
►
2月
(4)
►
1月
(11)
►
2017
(117)
►
12月
(14)
►
11月
(20)
►
10月
(17)
►
9月
(19)
►
8月
(10)
►
7月
(8)
►
6月
(3)
►
5月
(6)
►
4月
(5)
►
3月
(2)
►
2月
(8)
►
1月
(5)
►
2016
(91)
►
12月
(5)
►
11月
(9)
►
10月
(11)
►
9月
(9)
►
8月
(6)
►
7月
(14)
►
6月
(14)
►
5月
(11)
►
4月
(10)
►
3月
(2)
►
2015
(23)
►
12月
(4)
►
11月
(2)
►
10月
(8)
►
9月
(8)
►
7月
(1)
►
2013
(3)
►
11月
(1)
►
9月
(1)
►
7月
(1)
►
2012
(2)
►
7月
(1)
►
6月
(1)
►
2011
(1)
►
9月
(1)
►
2009
(1)
►
7月
(1)
►
2008
(2)
►
11月
(1)
►
7月
(1)
►
2007
(3)
►
10月
(3)