### Background Worker

Server Background Worker
Reference: https://www.b4x.com/android/forum/threads/server-background-workers.73269/
Example using WorkerClass
1) Excecutes a task every 5 seconds
2) The task method can also be called from the Main Class
Worker Class
`Sub Class_Globals
Private timer1 As Timer
End Sub`
`Public Sub Initialize
Main.Worker = Me
timer1.Initialize("timer1", 5000)
timer1.Enabled = True
Log("WorkerClass started")
'IMPORTANT to start the thread!
StartMessageLoop
End Sub`
`Sub Timer1_Tick
WorkerTask($"Task ${Rnd(1,100)}"$)
End Sub`
`Public Sub WorkerTask(task As String)
Log($"${DateTime.Time(DateTime.now)}: Worker Class executed Task ${task}"$)
End Sub`
Main Class
`Sub Process_Globals
Private srvr As Server
Public Worker As WorkerClass
'Timer running once to execute a worker task
Public timer1 As Timer
End Sub`
`Sub AppStart (Args() As String)
srvr.Initialize("srvr")
srvr.Port =51042
'Start the background worker = Must be set before the call to Server.Start.
srvr.AddBackgroundWorker("WorkerClass")
srvr.Start
Log("Server started")
timer1.Initialize("timer1", 2000)
timer1.Enabled = True
StartMessageLoop
End Sub`
'Return true to allow the default exceptions handler to handle the uncaught exception.
`Sub Application_Error (Error As Exception, StackTrace As String) As Boolean
Return True
End Sub`
`Sub Timer1_Tick
'Ensure worker is initialized, then run the worker task and stop the timer
If Worker.IsInitialized Then
CallSubDelayed2(Worker, "WorkerTask", "New Task")
timer1.Enabled = False
End If
End Sub`
Hints
Call the class from the server
'Must be set before the call to Server.Start.
srvr.AddBackgroundWorker("WorkerClass")
srvr.Start
Call Background Worker classMethod from Main class
Create a public variable in Main module and set it from the Initialize method of the worker class:
Main
Public Worker as WorkerClass
'Worker Class Init
`Sub Initialize
Main.Worker = Me
...
End Sub`
Use CallSubDelayed to call the worker methods to ensure being called by the background worker thread, ie (see example above)
CallSubDelayed2(Worker, "WorkerTask", "New Task")

Changed: , Category: Server, File: T6C246M1781.htm, ID: 1781