Timer 如何每15分钟重复一次自定义功能?(朱莉娅)

Timer 如何每15分钟重复一次自定义功能?(朱莉娅),timer,julia,Timer,Julia,我试图编写一个函数,将当前登录到oldschool runescape的玩家数量与当前时间和日期添加到csv文件中。这个函数工作得很好,但是当我尝试使用Timer函数多次重复该函数时,它显示了一个错误。(我希望它在空闲的笔记本电脑上每15分钟运行一次) 这就是功能: function countplayers() res = HTTP.get("https://oldschool.runescape.com") body = String(res.body);

我试图编写一个函数,将当前登录到oldschool runescape的玩家数量与当前时间和日期添加到csv文件中。这个函数工作得很好,但是当我尝试使用Timer函数多次重复该函数时,它显示了一个错误。(我希望它在空闲的笔记本电脑上每15分钟运行一次)

这就是功能:

function countplayers()
    res = HTTP.get("https://oldschool.runescape.com")
    body = String(res.body);
    locatecount = findfirst("There are currently", body);
    firstplayercount = body[locatecount[end]+2:locatecount[end]+8]
    first = firstplayercount[1:findfirst(',',firstplayercount)-1]
    if findfirst(',',firstplayercount) == 3
        second = firstplayercount[findfirst(',',firstplayercount)+1:end-1]
    else
        second = firstplayercount[findfirst(',',firstplayercount)+1:end]
    end
    finalcount = string(first,second)
    currentdate = Dates.now()
    concatenated = [finalcount, currentdate]
    f = open("test.csv","a")
    write(f, finalcount,',')
    write(f, string(currentdate), '\n')
    close(f)
end
如果我尝试
Timer(countplayers(),10,10)
来测试它,我会得到以下错误:

**ERROR: MethodError: no method matching Timer(::Nothing, ::Int64, ::Int64)**
如果计时器位于函数下方,并且REPL中使用了timer命令,则会出现相同的错误。
我做错了什么?提前谢谢

实现这一点的标准方法是启动异步任务,然后在循环中运行它,并在其间休眠:

@async while true
    my_function()
    sleep(15*60)
end

由于此块是异步的,因此评估将立即返回,任务将在后台运行,直到程序退出。

扩展Stefan的建议如何在此处开始,这是一个完整且非常有用的代码:

function dosomething(f, interval) 
    stopper = Ref(false)
    task = @async while !stopper[]
        f()
        sleep(interval)
    end
    return task, stopper
end
现在让我们看看这一行动:

julia> task, stopper = dosomething(()->println("Hello World"),10)
Hello World
(Task (runnable) @0x000000001675c5d0, Base.RefValue{Bool}(false))

julia> Hello World
julia>

julia> stopper[]=true;  # I do not want my background process anymore running


julia> task    #after few seconds the status will be done
Task (done) @0x000000001675c5d0

最后,还应注意,在生产系统中,通常最稳健的方法是使用系统工具,如
crontab
,来控制和管理此类重复事件。

除了其他答案之外,还有另一个解决方案,更符合您的尝试:

julia>使用日期
julia>函数countplayers()
println($(now())有42名玩家)
结束
countplayers(带1方法的通用函数)
#从现在开始,每3秒运行一次“CountPlayer”(延迟=0)
julia>t=Timer(->countplayers(),0,interval=3);
2020-11-10T17:52:42.904有42名球员
2020-11-10T17:52:45.896有42名球员
2020-11-10T17:52:48.899有42名球员
2020-11-10T17:52:51.902有42名选手
2020-11-10T17:52:54.905有42名球员
2020-11-10T17:52:57.908有42名球员
2020-11-10T17:53:00.909有42名球员
#当您想停止任务时
朱莉娅>关闭(t)

我尝试了两种方法(用10秒而不是15分钟):1)我尝试使用函数将异步添加到julia文件的末尾,2)我尝试在REPL中使用异步。在这两种情况下,该函数只执行一次,并且不会每10秒重复一次。对不起,我的回答应该使用
while true
循环,而不是
begin
块,它实际上只运行一次。更正。