Search code examples
rwindows-task-scheduler

Schedule R scripts without using Task Scheduler


I have RStudio installed on my Windows 7 machine however I am unable to access Windows Task Scheduler to automate some R scripts. Are there any alternatives in this situation? I have explored taskscheduleR however found out that this is just a wrapper of Task Scheduler. Open to ideas using VB scripts - basically any hack will do.


Solution

  • I would suggest VBA for your task and you need to learn how to use Application.OnTime;

    You need other subs that triggers and stops this one as you desire; first one can start the schedule.

    Public stop_running As Boolean
    Public sTime As String
    
    Sub Start(input As String)
    
        stop_running = True 'This controls schedule in Application.Ontime
        sTime = input
        Application.OnTime TimeValue(sTime), "Rscript", Schedule:=stop_running
    
    End Sub
    

    Whenever you want to stop running this macro, the you run this one;

    Sub Finish()
    
        stop_running = False 'Set the schedule to false to stop the macro
        Application.OnTime TimeValue(sTime), "Rscript", Schedule:=stop_running
    
    End Sub
    

    Then this is the sub that runs your r-script:

    Sub Rscript()
    'runs R script through cmd
    
        If Not stop_running Exit Sub
    
    Dim shell As Object
    Set shell = VBA.CreateObject("WScript.Shell")
    Dim waitTillComplete As Boolean: waitTillComplete = True
    Dim style As Integer: style = 1
    Dim errorCode As Integer
    Dim path As String
    
    path = "RScript C:\R\myscript.R"
    errorCode = shell.Run(path, style, waitTillComplete)
    
    End Sub
    

    You can call the macro Start from immediate window like this:

    Call Start(TimeValue("14:00:00 pm"))
    

    And your macro will run at 2 p.m. Everyday.