Skip to content

Feature/refine cronttab #790

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Dec 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,8 @@ public interface IBotSharpRepository : IHaveServiceProvider
#endregion

#region Crontab
bool InsertCrontabItem(CrontabItem cron) => throw new NotImplementedException();
bool UpsertCrontabItem(CrontabItem cron) => throw new NotImplementedException();
bool DeleteCrontabItem(string conversationId) => throw new NotImplementedException();
PagedItems<CrontabItem> GetCrontabItems(CrontabItemFilter filter) => throw new NotImplementedException();
#endregion
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public async Task<bool> Execute(RoleDialogModel message)
};

var db = _services.GetRequiredService<IBotSharpRepository>();
// var ret = db.InsertCrontabItem(crontabItem);
// var ret = db.UpsertCrontabItem(crontabItem);

return true;
}
Expand Down
32 changes: 20 additions & 12 deletions src/Infrastructure/BotSharp.Core.Crontab/Services/CrontabWatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,24 +46,32 @@ private async Task RunCronChecker(IServiceProvider services)
var crons = await cron.GetCrontable();
foreach (var item in crons)
{
var schedule = CrontabSchedule.Parse(item.Cron, new CrontabSchedule.ParseOptions
try
{
IncludingSeconds = true // Ensure you account for seconds
});
var schedule = CrontabSchedule.Parse(item.Cron, new CrontabSchedule.ParseOptions
{
IncludingSeconds = true // Ensure you account for seconds
});

// Get the current time
var currentTime = DateTime.UtcNow;
// Get the current time
var currentTime = DateTime.UtcNow;

// Get the next occurrence from the schedule
var nextOccurrence = schedule.GetNextOccurrence(currentTime.AddSeconds(-1));
// Get the next occurrence from the schedule
var nextOccurrence = schedule.GetNextOccurrence(currentTime.AddSeconds(-1));

// Check if the current time matches the schedule
bool matches = currentTime >= nextOccurrence && currentTime < nextOccurrence.AddSeconds(1);
// Check if the current time matches the schedule
bool matches = currentTime >= nextOccurrence && currentTime < nextOccurrence.AddSeconds(1);

if (matches)
if (matches)
{
_logger.LogDebug($"The current time matches the cron expression {item}");
cron.ScheduledTimeArrived(item);
}
}
catch (Exception ex)
{
_logger.LogDebug($"The current time matches the cron expression {item}");
cron.ScheduledTimeArrived(item);
_logger.LogWarning($"Error when running cron task ({item.ConversationId}, {item.Title}, {item.Cron}): {ex.Message}\r\n{ex.InnerException}");
continue;
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
using BotSharp.Abstraction.Crontab.Models;
using System.IO;

namespace BotSharp.Core.Repository;

public partial class FileRepository
{
public bool InsertCrontabItem(CrontabItem cron)
public bool UpsertCrontabItem(CrontabItem cron)
{
if (cron == null || string.IsNullOrWhiteSpace(cron.ConversationId))
{
Expand All @@ -32,6 +31,37 @@ public bool InsertCrontabItem(CrontabItem cron)
}
}

public bool DeleteCrontabItem(string conversationId)
{
if (string.IsNullOrWhiteSpace(conversationId))
{
return false;
}

try
{
var baseDir = Path.Combine(_dbSettings.FileRepository, _conversationSettings.DataDir, conversationId);
if (!Directory.Exists(baseDir))
{
return false;
}

var cronFile = Path.Combine(baseDir, CRON_FILE);
if (!File.Exists(cronFile))
{
return false;
}

File.Delete(cronFile);
return true;
}
catch (Exception ex)
{
_logger.LogError($"Error when deleting crontab item (${conversationId}): {ex.Message}\r\n{ex.InnerException}");
return false;
}
}


public PagedItems<CrontabItem> GetCrontabItems(CrontabItemFilter filter)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ namespace BotSharp.Plugin.MongoStorage.Repository;

public partial class MongoRepository
{
public bool InsertCrontabItem(CrontabItem item)
public bool UpsertCrontabItem(CrontabItem item)
{
if (item == null)
if (item == null || string.IsNullOrWhiteSpace(item.ConversationId))
{
return false;
}
Expand All @@ -16,7 +16,12 @@ public bool InsertCrontabItem(CrontabItem item)
{
var cronDoc = CrontabItemDocument.ToMongoModel(item);
cronDoc.Id = Guid.NewGuid().ToString();
_dc.CrontabItems.InsertOne(cronDoc);

var filter = Builders<CrontabItemDocument>.Filter.Eq(x => x.ConversationId, item.ConversationId);
var result = _dc.CrontabItems.ReplaceOne(filter, cronDoc, new ReplaceOptions
{
IsUpsert = true
});
return true;
}
catch (Exception ex)
Expand All @@ -27,6 +32,19 @@ public bool InsertCrontabItem(CrontabItem item)
}


public bool DeleteCrontabItem(string conversationId)
{
if (string.IsNullOrWhiteSpace(conversationId))
{
return false;
}

var filter = Builders<CrontabItemDocument>.Filter.Eq(x => x.ConversationId, conversationId);
var result = _dc.CrontabItems.DeleteMany(filter);
return result.DeletedCount > 0;
}


public PagedItems<CrontabItem> GetCrontabItems(CrontabItemFilter filter)
{
if (filter == null)
Expand All @@ -37,7 +55,7 @@ public PagedItems<CrontabItem> GetCrontabItems(CrontabItemFilter filter)
var cronBuilder = Builders<CrontabItemDocument>.Filter;
var cronFilters = new List<FilterDefinition<CrontabItemDocument>>() { cronBuilder.Empty };

// Filter conversations
// Filter cron
if (filter?.AgentIds != null)
{
cronFilters.Add(cronBuilder.In(x => x.AgentId, filter.AgentIds));
Expand Down