Files
caliverse_server/ServerBase/Entity/Task/EntityTicker.cs
2025-05-01 07:23:28 +09:00

108 lines
2.7 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ServerCore; using ServerBase;
namespace ServerBase;
public abstract class EntityTicker : EntityBase, ITaskTicker
{
private double m_tick_interval_milliseconds;
private PeriodicTaskTimer? m_timer_nullable;
private readonly CancellationTokenSource m_cancel_token;
private readonly bool m_is_cancel_by_self;
public EntityTicker( EntityType entityType
, double onTickIntervalMilliseconds, CancellationTokenSource? toCancelToken )
: base(entityType)
{
m_tick_interval_milliseconds = onTickIntervalMilliseconds;
if(null == toCancelToken)
{
m_cancel_token = new();
m_is_cancel_by_self = true;
}
else
{
m_cancel_token = toCancelToken;
m_is_cancel_by_self = false;
}
}
public EntityTicker(EntityType entityType, EntityBase parent, Int32 onTickIntervalMilliseconds, CancellationTokenSource? toCancelToken)
: base(entityType, parent)
{
m_tick_interval_milliseconds = onTickIntervalMilliseconds;
if(null == toCancelToken)
{
m_cancel_token = new();
m_is_cancel_by_self = true;
}
else
{
m_cancel_token = toCancelToken;
m_is_cancel_by_self = false;
}
}
public override async Task<Result> onInit()
{
return await onCreateTask();
}
public virtual async Task<Result> onCreateTask()
{
await Task.CompletedTask;
var result = new Result();
try
{
m_timer_nullable = new PeriodicTaskTimer( GetType().Name
, getOnTickIntervalMilliseconds()
, getCancelToken(), onTaskTick );
}
catch(Exception e)
{
var err_msg = $"Exception !!!, new PeriodicTaskTimer() : exception:{e} - {toBasicString()}";
result.setFail(ServerErrorCode.TryCatchException, err_msg);
return result;
}
return result;
}
public abstract Task onTaskTick();
public async Task onTaskWait()
{
if (m_timer_nullable != null)
await m_timer_nullable.getTask();
}
public void cancel()
{
if(true == m_is_cancel_by_self)
{
m_timer_nullable?.cancelTimer();
}
}
public double getOnTickIntervalMilliseconds() => m_tick_interval_milliseconds;
public CancellationTokenSource getCancelToken() => m_cancel_token;
public PeriodicTaskTimer? getPeriodicTaskTimer() => m_timer_nullable;
}