除了手动添加 job 还可以写代码添加

优质
小牛编辑
131浏览
2023-12-01

Hangfire.HttpJob.Client 组件

Install-Package Hangfire.HttpJob.Client

  • 支持 net framework 4.5+
  • 支持 net standard 2.0+

如何使用Client新增一次性运行的 job

参数是和在dashbord上手动添加一致的,关于参数的说明请参考: job 参数说明

// serverUrl是hangfire dashbord的访问地址

    var serverUrl = "http://localhost:5000/job";
    //下面用的是同步的方式,也可以使用异步: await HangfireJobClient.AddBackgroundJobAsync
    var result = HangfireJobClient.AddBackgroundJob(serverUrl, new BackgroundJob
    {
        JobName = "测试api",
        Method = "Get",
        Url = "http://localhost:5000/testaaa"
        SendSuccess = true,
        DelayFromMinutes = 1 //这里是在多少分钟后执行
       //RunAt = new DateTime(2020,7,25,10,5,1) // 也可以不用指定 DelayFromMinutes 参数 直接指定在什么时候运行。
    }, new HangfireServerPostOption
    {
        BasicUserName = "admin",//这里是hangfire设置的basicauth
        BasicPassword = "test"//这里是hangfire设置的basicauth
    });

    //result.JobId 就是这个一次性job的id 可以通过这个id在它没有运行前删除它

如何使用Client删除刚刚创建的一次性运行的job

    var serverUrl = "http://localhost:5000/job";
    var result = HangfireJobClient.RemoveBackgroundJob(serverUrl, jobId, new HangfireServerPostOption
    {
        BasicUserName = "admin",//这里是hangfire设置的basicauth
        BasicPassword = "test"//这里是hangfire设置的basicauth
    });

BackgroundJob 不支持修改。如果创建后要修改 就得删除后重新创建

如何使用Client新增一个周期性运行的 job

参数是和在dashbord上手动添加一致的,关于参数的说明请参考: 周期性运行的 job 参数说明

    var serverUrl = "http://localhost:5000/job";
    //下面用的是同步的方式,也可以使用异步: await HangfireJobClient.AddRecurringJobAsync
    var result = HangfireJobClient.AddRecurringJob(serverUrl, new RecurringJob()
    {
        JobName = "测试5点40执行",
        Method = "Post",
        Data = new {name = "aaa",age = 10},
        Url = "http://localhost:5000/testpost"
        Cron = "40 17 * * *"
    }, new HangfireServerPostOption
    {
        BasicUserName = "admin",//这里是hangfire设置的basicauth
        BasicPassword = "test"//这里是hangfire设置的basicauth
    });

RecurringJob如果同一个JobName多次调用创建 就等同于修改。删除可以调用 RemoveRecurringJob 进行删除