将方法传递给 Hangfire Scheduler 的另一个方法,而不是使用硬编码的方法名称

Passing a method to another method for Hangfire Scheduler instead of using a hardcoded method name

我正在使用 Hangfire 并试图安排一个简单的工作。如果我硬编码要在指定时间触发的方法的名称,它会起作用,但我想要更通用的东西,即将任何方法传递到此代码并让 Hangfire 按计划执行它。

这是我尝试过的方法之一。

public static void ScheduleSingleRun(Activity parametersStorage, Action<Activity, int> scheduledFunction, int secondsDelay)
{
    TimeSpan offset = new TimeSpan(0, 0, secondsDelay);
    try
    {
        BackgroundJob.Schedule(() => 
            scheduledFunction(parametersStorage, secondsDelay), offset);
        return new HangfireSchedulerResponse("Scheduled successfully.", 0);          
        ... 

我是这样调用这个函数的:

HangfireScheduler.ScheduleSingleRun(parameters, TestMethod, 15);

其中 TestMethod 是同一个方法的名称 class。

此代码编译,但在 运行:

时导致此错误
Expression body should be of type `MethodCallExpression`"

我尝试了 Action、Func<>、Delegate - 没有任何效果。仅指定显式方法名称有效:

BackgroundJob.Schedule(() => TestClass.TestMethod(parametersStorage, secondsDelay)

我做错了什么 - 有没有办法将方法 name/reference 传递给 Hangfire 而不是对其进行硬编码?

参见下面的示例。在你的情况下,我认为你必须传递一个表达式。在我的示例中,您应该将 "lambda" 变量传递给您的 BackgroundJob.Schedule 方法。

class Program
{
    static void Main(string[] args)
    {
        int param1Value = 2;
        object param2Value = "hello";

        var param1 = Expression.Parameter(typeof(int));
        var param2 = Expression.Parameter(typeof(object));

        var testMethodInfo = typeof(MyClass).GetMethod("TestMethod", BindingFlags.Public | BindingFlags.Static);
        var exp = Expression.Call(testMethodInfo, param1, param2);

        var lambda = Expression.Lambda<Action<int, object>>(exp, param1, param2);

        lambda.Compile().Invoke(param1Value, param2Value);
    }
}

static class MyClass
{
    public static void TestMethod(int param1, object param2)
    {
        Console.WriteLine(param1);
        Console.WriteLine(param2?.ToString());
    }
}