summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--Jobs/LoggerJob.cs36
-rw-r--r--Program.cs4
-rw-r--r--wwwroot/Log.txt12
3 files changed, 52 insertions, 0 deletions
diff --git a/Jobs/LoggerJob.cs b/Jobs/LoggerJob.cs
new file mode 100644
index 0000000..72a571f
--- /dev/null
+++ b/Jobs/LoggerJob.cs
@@ -0,0 +1,36 @@
+// Singleton service.
+namespace BackendPIA.Jobs {
+ public class LoggerJob : IHostedService {
+ private Timer? _timer;
+ private readonly IWebHostEnvironment _env;
+ private readonly string _log_file = "Log.txt";
+
+ public LoggerJob(IWebHostEnvironment env) {
+ _env = env;
+ }
+
+ public Task StartAsync(CancellationToken cancel_token) {
+ _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromMinutes(5));
+
+ return Task.CompletedTask;
+ }
+
+ public void DoWork(object state) {
+ LogToFile("Executing task\n" + DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss"));
+ }
+
+ public Task StopAsync(CancellationToken cancel_token) {
+ LogToFile("Stopping task...\n");
+ _timer.Dispose();
+ return Task.CompletedTask;
+ }
+
+ private void LogToFile(string message) {
+ var path = $@"{_env.ContentRootPath}/wwwroot/{_log_file}";
+
+ using (StreamWriter w = new StreamWriter(path, append: true)) {
+ w.WriteLine(message);
+ }
+ }
+ }
+} \ No newline at end of file
diff --git a/Program.cs b/Program.cs
index 793aa1e..3df7c40 100644
--- a/Program.cs
+++ b/Program.cs
@@ -9,6 +9,7 @@ using System.Text;
using Microsoft.EntityFrameworkCore;
using BackendPIA;
using BackendPIA.Models;
+using BackendPIA.Jobs;
using BackendPIA.Policies;
using BackendPIA.Services;
@@ -26,6 +27,9 @@ builder.Services.AddIdentity<UserAccount, IdentityRole>().AddEntityFrameworkStor
// Automapper configuration.
builder.Services.AddAutoMapper(typeof(Program));
+// Hosted services.
+builder.Services.AddHostedService<LoggerJob>();
+
// Custom services configuration.
builder.Services.AddSingleton<ITokenGenerator>(s => new TokenGenerator(builder.Configuration["Jwt:Key"]));
builder.Services.AddScoped<IGameService, GameService>();
diff --git a/wwwroot/Log.txt b/wwwroot/Log.txt
new file mode 100644
index 0000000..edf5f19
--- /dev/null
+++ b/wwwroot/Log.txt
@@ -0,0 +1,12 @@
+Executing task
+27/11/2022 01:22:08
+Stopping task...
+
+Executing task
+27/11/2022 01:25:41
+Executing task
+27/11/2022 01:30:41
+Executing task
+27/11/2022 01:35:41
+Stopping task...
+