Reusable/Generic RecurringJob

Hi all,

we want to create a generic class which monitors a directory using a RecurringJob. Once a file is dropped in that directory, it should be moved to a new directory and a new BackgroundJob should be enqueued.

We were thinking about the following class:

 public class MonitorDirectoryJob
    {
        public MonitorDirectoryJob(string source, string dirToMonitor, string targetDir, Expression<Action<string>> methodCall)
        {
            RecurringJob.AddOrUpdate(RecurringJobId(source), () => WatchDirectory(dirToMonitor, targetDir, methodCall), Cron.Minutely);
        }

        public static void WatchDirectory(string dirToMonitor, string targetDir, Expression<Action<string>> methodCall)
        {
            DirectoryInfo dir = new DirectoryInfo(dirToMonitor);
            dir.GetFiles()
                .ForEach(file =>
                {
                    var destFileName = Path.Combine(targetDir, file.Name, file.Extension);
                    file.MoveTo(destFileName);
                    
                    BackgroundJob.Enqueue(() => methodCall.Compile()(destFileName));
                });
        }

        private static string RecurringJobId(string source)
        {
            return "monitor-dir-" + source;
        }
    }

Usage would be as follows:

 public void Test()
        {
            new MonitorDirectoryJob("source", @"C:\temp\batch\in", @"C:\temp\batch\processing", filePath => DoStuffWithFile(filePath));
        }

        public static void DoStuffWithFile(string filePath)
        {
            Debug.WriteLine(filePath);
        }

However, we get an exception when viewing the RecurringJob in Hangfire telling us that the expression can’t be serialized to JSON. Any idea if this is possible somehow?

The error in Hangfire

Unable to find a constructor to use for type System.Linq.Expressions.Expression`1[System.Action`1[System.String]]. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Path 'Type', line 1, position 8.

Thanks in advance,
Ronald