CsharpTemplate/ConsoleTemplate/Services/TimerService.cs

116 lines
3.2 KiB
C#
Raw Normal View History

2023-10-27 19:00:41 +07:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using ConsoleTemplate.Repositories;
using Microsoft.Extensions.Configuration;
namespace ConsoleTemplate.Services
{
internal class TimerService
{
private LogService _log;
private IRepository _repo;
private IConfiguration _config;
private System.Timers.Timer _tmr;
private DateTime _tglRequest;
private int _jumlahTread;
public TimerService(LogService logger, IRepository rorepository, IConfiguration config)
{
_log = logger;
_repo = rorepository;
_config = config;
}
public void Start(DateTime tanggalProses, int jmlthread)
{
_repo.InitDB();
_tglRequest = tanggalProses;
_jumlahTread = jmlthread;
Conf.Load(_repo, _config);
_log.Info("Timer Start");
_tmr = new System.Timers.Timer(5000);
_tmr.Elapsed += CekRequest;
_tmr.Start();
Console.ReadLine();
}
private void CekRequest(object sender, ElapsedEventArgs e)
{
_tmr.Stop();
try
{
long totalRequest = 0; // _repo.GetTotalRequest(_tglRequest);
if (totalRequest > 0)
{
//List<Request> _requestList = _repo.GetRequests(_tglRequest);
ProceedRequest();
}
else if (true)
{
}
}
catch (Exception ex)
{
_log.Error("Error CekRequest : " + ex.Message);
}
_tmr.Start();
}
private void ProceedRequest()
{
try
{
List<Thread> ThreadList = new List<Thread>();
for (int i = 0; i < _jumlahTread; i++)
{
ThreadList.Add(new Thread(DummyProcess));
ThreadList[i].Name = "Thread" + i;
}
for (int i = 0; i < 10; i++)
{
int k = Array.FindIndex(ThreadList.ToArray(), IsThreadAvailable);
if (k >= 0)
{
ThreadList[k] = new Thread(() => DummyProcess());
ThreadList[k].Start();
}
while (Array.FindAll(ThreadList.ToArray(), IsThreadAvailable).Length == 0 ||
(i == 10 & Array.FindAll(ThreadList.ToArray(), IsThreadRunning).Length > 0))
Thread.Sleep(5000);
}
}
catch (Exception ex)
{
_log.Error("Error ProceedRequest : " + ex.Message);
}
}
private void DummyProcess() { }
private bool IsThreadAvailable(Thread t)
{
return t.ThreadState != ThreadState.Running && t.ThreadState != ThreadState.WaitSleepJoin;
}
private bool IsThreadRunning(Thread t)
{
return t.ThreadState == ThreadState.Running || t.ThreadState == ThreadState.WaitSleepJoin;
}
}
}