Skip to content

Commit

Permalink
Crons and config
Browse files Browse the repository at this point in the history
  • Loading branch information
Glowstudent777 committed Apr 8, 2024
1 parent fb11bc1 commit 8237d99
Show file tree
Hide file tree
Showing 10 changed files with 199 additions and 6 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ This is a Discord bot template made in C# using .Net 7
- [x] Database
- [x] Organized Layout
- [x] Nice Logs
- [ ] Cron Jobs
- [x] Cron Jobs

## Cloning

Expand Down
38 changes: 38 additions & 0 deletions src/Houston.Bot/Crons/JobFactory.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Quartz;
using Quartz.Spi;

namespace Houston.Bot.Crons;

public class JobFactory : IJobFactory
{
private readonly IServiceProvider _serviceProvider;

public JobFactory(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}

public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
{
var jobDetail = bundle.JobDetail;
var jobType = jobDetail.JobType;
var jobInstance = _serviceProvider.GetService(jobType);

if (jobInstance == null || !(jobInstance is IJob))
{
throw new SchedulerException($"Failed to create job of type {jobType.FullName}");
}

return jobInstance as IJob;
}

public void ReturnJob(IJob job)
{
}
}
46 changes: 46 additions & 0 deletions src/Houston.Bot/Crons/Jobs/ExampleJob.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
using Quartz;
using System;
using System.Threading.Tasks;
using Houston.Bot.Common;
using Microsoft.Extensions.Logging;
using Discord.WebSocket;
using Houston.Bot.Services;

namespace Houston.Bot.Crons.Jobs;

[DisallowConcurrentExecution]
public class ExampleJob : IJob
{
private readonly ILogger<ExampleJob> _logger;
public ExampleJob(ILogger<ExampleJob> logger)
{
_logger = logger;
}

public Task Execute(IJobExecutionContext context)
{
try
{
Console.WriteLine("ExampleJob executed");
}
catch (Exception ex)
{
_logger.LogError(ex, "Error while cleaning up expired keys");
}
return Task.CompletedTask;
}

public static ITrigger GetTrigger()
{
return TriggerBuilder.Create()
.WithIdentity("ExampleJob-trigger")
.WithSimpleSchedule(x =>
{
x.WithRepeatCount(0);
x.WithMisfireHandlingInstructionNextWithRemainingCount();
})
.StartAt(DateTimeOffset.Now.AddSeconds(15))
.ForJob("ExampleJob")
.Build();
}
}
23 changes: 23 additions & 0 deletions src/Houston.Bot/Crons/ScheduleJobs.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using Houston.Bot.Crons.Jobs;
using Houston.Bot.Services;
using Microsoft.Extensions.DependencyInjection;
using Quartz;

namespace Houston.Bot.Crons;

public class ScheduleJobs
{
private readonly JobSchedulerService _jobSchedulerService;
private readonly IServiceProvider _serviceProvider;

public ScheduleJobs(JobSchedulerService jobSchedulerService, IServiceProvider serviceProvider)
{
_jobSchedulerService = jobSchedulerService;
_serviceProvider = serviceProvider;
}

public async Task ScheduleAllJobs()
{
await _jobSchedulerService.ScheduleJob<ExampleJob>("ExampleJob", ExampleJob.GetTrigger());
}
}
5 changes: 4 additions & 1 deletion src/Houston.Bot/Houston.Bot.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,13 @@

<ItemGroup>
<PackageReference Include="Discord.Addons.Hosting" Version="5.2.0" />
<PackageReference Include="Discord.Net" Version="3.13.0-20231203.4" />
<PackageReference Include="Discord.Net" Version="3.14.1" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting.Systemd" Version="8.0.0" />
<PackageReference Include="Quartz" Version="3.8.1" />
<PackageReference Include="Quartz.Extensions.DependencyInjection" Version="3.8.1" />
<PackageReference Include="Quartz.Extensions.Hosting" Version="3.8.1" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Extensions.Hosting" Version="8.0.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
Expand Down
19 changes: 18 additions & 1 deletion src/Houston.Bot/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@
using Serilog;
using Houston.Database;
using Discord.Addons.Hosting;
using Microsoft.Extensions.Logging;
using Houston.Bot.Crons;
using Quartz;
using Houston.Bot.Crons.Jobs;

namespace Houston.Bot;

Expand All @@ -28,8 +32,15 @@ private static async Task Main(string[] args)
{
config.Token = Environment.GetEnvironmentVariable("TOKEN");
})
.ConfigureLogging((context, logging) =>
{
logging.ClearProviders();
})
.Build();

var jobSchedulerService = host.Services.GetRequiredService<JobSchedulerService>();
await jobSchedulerService.Start();

Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(host.Services.GetRequiredService<IConfiguration>())
.CreateLogger();
Expand Down Expand Up @@ -64,13 +75,19 @@ private static async Task Main(string[] args)

private static void ConfigureServices(HostBuilderContext context, IServiceCollection services)
{
services.AddSingleton(typeof(Microsoft.Extensions.Logging.ILogger<>), typeof(Logger<>));
services.AddSingleton(typeof(Microsoft.Extensions.Logging.ILogger<>), typeof(Services.Logger<>));

services.AddDbContext<DatabaseContext>();

services.AddSingleton<InteractionService>();
services.AddHostedService<InteractionHandlingService>();

services.AddQuartz(q => q.UseJobFactory<JobFactory>());
services.AddSingleton<JobSchedulerService>();
services.AddSingleton<ScheduleJobs>();

services.AddSingleton<ExampleJob>();

services.AddHostedService<BotService>();
}
}
65 changes: 65 additions & 0 deletions src/Houston.Bot/Services/JobSchedulerService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
using Quartz;
using Quartz.Impl;
using Houston.Bot.Crons;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Quartz.Spi;
using System;

namespace Houston.Bot.Services;

public class JobSchedulerService
{
private readonly IScheduler _scheduler;
private readonly IJobFactory _jobFactory;
private readonly IServiceProvider _serviceProvider;

public JobSchedulerService(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
_scheduler = new StdSchedulerFactory().GetScheduler().GetAwaiter().GetResult();
_jobFactory = new JobFactory(serviceProvider);
}

public async Task Start()
{
_scheduler.JobFactory = _jobFactory;
await _scheduler.Start();

var scheduleJobs = _serviceProvider.GetRequiredService<ScheduleJobs>();
await scheduleJobs.ScheduleAllJobs();
}

public async Task Stop()
{
await _scheduler.Shutdown();
}

public async Task PauseJob(string jobName)
{
var jobKey = new JobKey(jobName);
await _scheduler.PauseJob(jobKey);
}

public async Task ResumeJob(string jobName)
{
var jobKey = new JobKey(jobName);
await _scheduler.ResumeJob(jobKey);
}

public async Task DeleteJob(string jobName)
{
var jobKey = new JobKey(jobName);
await _scheduler.DeleteJob(jobKey);
}

public async Task ScheduleJob<T>(string jobName, ITrigger trigger) where T : IJob
{
IJobDetail job = JobBuilder.Create<T>()
.WithIdentity(jobName)
.Build();

await _scheduler.ScheduleJob(job, trigger);
}
}
2 changes: 1 addition & 1 deletion src/Houston.Bot/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
"Args": {
"path": "Logs/log_.txt",
"rollingInterval": "Day",
"restrictedToMinimumLevel": "Information",
"restrictedToMinimumLevel": "Debug",
"outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3} {SourceContext}] {Message}{NewLine}{Exception}"
}
}
Expand Down
3 changes: 2 additions & 1 deletion src/Houston.Database/DatabaseContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ public class DatabaseContext : DbContext

public DatabaseContext(IConfiguration configuration)
{
_connectionString = Environment.GetEnvironmentVariable("DATABASE");
_connectionString = Environment.GetEnvironmentVariable("DATABASE") ?? configuration["profiles:Houston.Bot:environmentVariables:DATABASE"];

}

protected override void OnConfiguring(DbContextOptionsBuilder options)
Expand Down
2 changes: 1 addition & 1 deletion src/Houston.Database/DesignTimeDatabaseContextFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public class DesignTimeDatabaseContextFactory : IDesignTimeDbContextFactory<Data
public DatabaseContext CreateDbContext(string[] args)
{
var configuration = new ConfigurationBuilder()
.AddJsonFile(Directory.GetCurrentDirectory() + "/../Houston.Bot/appsettings.json")
.AddJsonFile(Directory.GetCurrentDirectory() + "/../Houston.Bot/Properties/launchSettings.json")
.Build();

return new DatabaseContext(configuration);
Expand Down

0 comments on commit 8237d99

Please sign in to comment.