---
title: "エージェントを作成する"
slug: "create-an-agent"
abstract: ""
---
# エージェントを作成する

BaseAgentまたはRecurringAgentを継承するエージェントを作成でき、そのエージェントがスケールするかどうかを選択できます。カスタムエージェントを作成する理由には以下があります:

-   エンジン内で定期的にメンテナンスを行い、例えばエンジンが依存するデータベースから期限切れデータを消去します。デフォルトでは、処理エンジンには保守タスクを実行する2つのエージェントが含まれています。

> !注カスタムエージェントを作成する必要は稀です。むしろ、デフォルトのTaskAgentで実行されるカスタムプロセッシングワーカーを作成する可能性が高いです。

## RecurringAgentを継承するエージェントを作成する

以下のサンプルエージェントは、偽のストレージプロバイダー内のデータをクリーンアップするメソッドを呼び出します。ストレージプロバイダーはICustomProviderインターフェースで表現されます。エージェントはRecurringAgentを継承し、これは規則的かつ設定可能な間隔で実行されることを意味します。

### エージェントクラスを作成する

エージェントクラスを作成するには:

-   クラスを作成し、以下のサンプルエージェントをコピーします。

> !注サンプルICustomProviderとCustomProviderクラスは利便性のため同じファイルに含まれています。

using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Sitecore.Framework.Conditions;
using Sitecore.Processing.Engine.Abstractions;
using Sitecore.Processing.Engine.Agents;

namespace Sitecore.Documentation.Examples
{
 /// <summary>
 /// Provides basic agent functionality and services.
 /// </summary>
 public class SampleCleanupAgent : RecurringAgent
 {
 private readonly ICustomProvider \_customProvider;

 /// <summary>
 ///
 /// </summary>
 /// <param name="logger"></param>
 /// <param name="options"></param>
 /// <param name="customProvider"></param>
 protected SampleCleanupAgent(ILogger<IAgent> logger, IConfiguration options, ICustomProvider customProvider) : base(options, logger)
 {
 Condition.Requires(customProvider, nameof(customProvider)).IsNotNull();

 \_customProvider = customProvider;
 }

 /// <summary>
 ///
 /// </summary>
 /// <param name="token"></param>
 /// <returns></returns>
 protected override async Task RecurringExecuteAsync(CancellationToken token)
 {
 // Checks if cancellation has been requested in case task is long-running
 // It is your responsibility to check the status of the cancellation token
 while (!token.IsCancellationRequested)
 {
 await \_customProvider.CleanData().ConfigureAwait(false);
 }
 }
 }

 /// <summary>
 ///
 /// </summary>
 public interface ICustomProvider {
 /// <summary>
 ///
 /// </summary>
 /// <returns></returns>
 Task GetData();
 /// <summary>
 ///
 /// </summary>
 /// <returns></returns>
 Task CleanData();
 }

 /// <summary>
 ///
 /// </summary>
 public class CustomProvider : ICustomProvider
 {
 /// <summary>
 ///
 /// </summary>
 /// <returns></returns>
 public async Task CleanData()
 {
 // Clean up data in custom data provider
 await Task.Delay(1).ConfigureAwait(false);
 }

 /// <summary>
 ///
 /// </summary>
 /// <returns></returns>
 public async Task GetData()
 {
 // Get data from custom data provider
 await Task.Delay(1).ConfigureAwait(false);
 }
 }
}

### 設定中のレジスタエージェントとサービス

1.  scという名前のファイルを作成します。Processing.Engine.CustomAgents.xml \\\\App\_Data\\\\Config\\\\Globalに。
2.  レジスタは SampleCleanupAgent と ICustomProvider を示します。この例では、単一のエージェントを登録するためのシンプルな設定を用いています。

<Settings>
 <Sitecore>
 <Processing>
 <Services>
 <ICustomProvider>
 <Type>Sitecore.Documentation.Examples.CustomProvider, Sitecore.Documentation.Examples</Type>
 <As>Sitecore.Documentation.Examples.ICustomProvider, Sitecore.Documentation.Examples</As>
 <LifeTime>Transient</LifeTime>
 </ICustomProvider>
 <SampleCleanupAgent>
 <Type>Sitecore.Documentation.Examples.SampleCleanupAgent, Sitecore.Documentation.Examples</Type>
 <As>Sitecore.Processing.Engine.Abstractions.IAgent, Sitecore.Processing.Engine.Abstractions</As>
 <LifeTime>Transient</LifeTime>
 <Options>
 <!-- The period which the agent sleeps before running again. -->
 <SleepPeriod>0.\`00:00\`:14.000</SleepPeriod>
 </Options>
 </SampleCleanupAgent>
 </Services>
 </Processing>
 </Sitecore>
 </Settings>

あるいは、エージェントがスケールする必要がある場合は、ParallelAgentsConfigurationを使って登録してください:

<Settings>
 <Sitecore>
 <Processing>
 <Services>
 <ICustomProvider>
 <Type>Sitecore.Documentation.Examples.CustomProvider, Sitecore.Documentation.Examples</Type>
 <As>Sitecore.Documentation.Examples.ICustomProvider, Sitecore.Documentation.Examples</As>
 <LifeTime>Transient</LifeTime>
 </ICustomProvider>
 <SampleCleanupAgent>
 <Type>Sitecore.Processing.Engine.Agents.ParallelAgentsConfiguration, Sitecore.Processing.Engine</Type>
 <As>Sitecore.XConnect.DependencyInjection.Abstractions.IXConnectServicesConfiguration, Sitecore.XConnect.DependencyInjection</As>
 <LifeTime>Transient</LifeTime>
 <Options>
 <AgentFixedCount>0</AgentFixedCount>
 <AgentCoreRatio>0.75</AgentCoreRatio>
 <AgentConfiguration>
 <Type>Sitecore.Documentation.Examples.SampleCleanupAgent, Sitecore.Documentation.Examples</Type>
 <As>Sitecore.Processing.Engine.Abstractions.IAgent, Sitecore.Processing.Engine.Abstractions</As>
 <LifeTime>Transient</LifeTime>
 <Options>
 <SleepPeriod>0.\`00:00\`:14.000</SleepPeriod>
 </Options>
 </AgentConfiguration>
 </Options>
 </SampleCleanupAgent>
 </Services>
 </Processing>
 </Sitecore>
 </Settings>

## BaseAgentを継承するエージェントを作成します

以下のサンプルエージェントは起動時にログにメッセージを書き込み、1ミリ秒待ちます。エージェントは継承RecurringAgentせず、定期的に実行されません。

> !重要このエージェントはエンジン起動時に一度だけ実行されます。しかし、エージェントは特定のイベントが発生するまでスリープし、その後そのイベントが再び起こるまでスリープすることがあります。エージェントは技術的には「再発」しますが、定期的なスケジュールされた間隔ではありません。

### エージェントクラスを作成する

エージェントクラスを作成するには:

-   クラスを作成し、以下のサンプルエージェントをコピーします。
    
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.Logging;
    using Sitecore.Processing.Engine.Abstractions;
    using Sitecore.Processing.Engine.Agents;
    
    namespace Sitecore.Documentation.Examples
    {
     /// <summary>
     /// Provides basic agent functionality and services.
     /// </summary>
     public class SampleLogAgent : BaseAgent
     {
     /// <summary>
     ///
     /// </summary>
     /// <param name="logger"></param>
     /// <param name="options"></param>
     protected SampleLogAgent(ILogger<IAgent> logger, IConfiguration options) : base(logger, options)
     {
     }
    
     /// <summary>
     ///
     /// </summary>
     /// <param name="token"></param>
     /// <returns></returns>
     public override async Task ExecuteAsync(CancellationToken token)
     {
     // Write a custom log message
     // No cancellation token check in this example as task is unlikely to be long-running
     base.Log.LogInformation("Your custom agent has started.");
     await Task.Delay(1).ConfigureAwait(false);
     }
     }
    }
    

### 設定中のレジスタエージェント

1.  scという名前のファイルを作成します。Processing.Engine.CustomAgents.xml \\\\App\_Data\\\\Config\\\\Globalに。
    
2.  レジスタSampleCleanupAgent示す通り。この例では、単一エージェントを登録するためのシンプルな構成を用いています。
    
    <Settings>
     <Sitecore>
     <Processing>
     <Services>
     <SampleLogAgent>
     <Type>Sitecore.Documentation.Examples.SampleLogAgent, Sitecore.Documentation.Examples</Type>
     <As>Sitecore.Processing.Engine.Abstractions.IAgent, Sitecore.Processing.Engine.Abstractions</As>
     <LifeTime>Transient</LifeTime>
     </SampleLogAgent>
     </Services>
     </Processing>
     </Sitecore>
     </Settings>
    

## タスクキャンセル

長期的なタスクにつながる可能性のあるエージェントを実装する場合は、token.IsCancellationRequestedExecuteAsync方法(BaseAgent相続エージェントの場合)またはRecurringExecuteAsyncメソッド(エージェントがRecurringAgentを継承する場合)でプロパティを確認するようにしてください。