This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
bigbaddevil6's profile picture

Timer That Can Run Parallel With Other Functions

Started by bigbaddevil6, 13 September 2013 - 12:16 AM
bigbaddevil6 #1
Posted 13 September 2013 - 02:16 AM
So I was wondering what would be the best way of making a timer that can run while also waiting for other input. I do know of doing it in this way. Just an example.

user = "placeholder" -- this is only temp it get replaced using a different program. Only put it here so that there werent empty, random declarations

function timer()
   sleep(10)
   random = math.random(0,2)
   if random == 0 then print("Random message 1")
   elseif random == 1 then print("Random message 2")
   elseif random == 2 then print("Random message 3")
   end
end

local function check()
local event, player, message = os.pullEvent("chat")
if player == user then
  local comStr = string.match(message, "^turtle:%s*(.*)")
   if comStr then
	for word in string.gmatch(message, "(%S+)") do
	 if commands[word] then
	  commands[word]()
	 end
	end
   end
  end
end


while true do
   parallel.waitForAny(check, timer)
end
--I do not have the array/table list here to go with the check(), but its in a different file, plus I mainly wondering about the timer portion.

Now I am 90% sure that this is the wrong way to go about doing a well designed timer, so what would you guys suggest I do instead. The main point for this code will to be a random message at random times while still being able to accept arguments from the user to run other functions.
Asdramelesh #2
Posted 13 September 2013 - 08:53 AM
Hi, i'm not sure of what u need but maybe u can use os.startTimer()
http://computercraft.info/wiki/Os.startTimer
bigbaddevil6 #3
Posted 14 September 2013 - 03:56 AM
well i tired doing something like this for testing.

function idleTimer()
  os.startTimer(3)
  os.pullEvent("timer")
  print("Timed Out")
end


function readInput()
  input = read()
  print(input)
end


while true do
  parallel.waitForAny(idleTimer, readInput)
end


All that this does though is after you make a few input it gets to a point where it starts spamming "Timed Out". I'm not sure how to use the os.startTimer().

Also I don't know if I'm right or not cause again haven't used this but on the CC wiki in the link Asdramelesh provided. the example code shows this.

os.startTimer(3)
os.pullEvent(timer)

Shouldn't the timer have " " around it like this?


os.startTimer(3)
os.pullEvent("timer")
TheOddByte #4
Posted 15 September 2013 - 05:59 AM
An example code for you


someTimer = os.startTimer(10)
while true do
evt, p1 = os.pullEvent()

if evt == "timer" then

if p1 == someTimer then --Checking which timer that finished
print("someTimer has finished")

   someTimer = os.startTimer(10) --Starting the timer again when it has finished

print("Started someTimer again")
      end
   end
end