Skip to content

Instantly share code, notes, and snippets.

@tomohiro
Created December 24, 2010 09:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tomohiro/754046 to your computer and use it in GitHub Desktop.
Save tomohiro/754046 to your computer and use it in GitHub Desktop.
入力を待ち受けつつバックグラウンドで定期処理

仕様

  1. 文字列 Hoge, Fuga, Hago を 3秒置きに順に表示する
  2. 処理1を無限ループさせ,バックグラウンド処理にする
  3. ユーザの入力を待ち受けて,入力内容をそのまま出力する
var messages = ['Hoge', 'Fuga', 'Hago'];
var interval = 3000;
var i = 0;
var last = messages.length - 1;
var loop = function() {
console.log(messages[i]);
i == last ? i = 0 : i++;
setTimeout(loop, interval);
};
loop();
do {
input = prompt();
console.log(input);
} while (input);
#!/usr/bin/env lua
-- うまくいってない
loop = coroutine.create(
function()
local messages = {'Hoge', 'Fuga', 'Hago'}
while true do
for k, v in pairs(messages) do
print(v)
end
end
end
)
interval = 3
while true do
local start = os.time()
coroutine.resume(loop)
repeat print(io.read()) until os.time() < start + interval
end
<?php
/* Clean (erase) the output buffer and turn off output buffering */
ob_end_clean();
/* うまくいってない */
$messages = array('Hoge', 'Fuga', 'Hago');
$interval = 3;
while (true) {
foreach ($messages as $v) {
echo $v . PHP_EOL;
sleep($interval);
}
}
while ($line = trim(fgets(STDIN))) {
echo $line . PHP_EOL;
}
#!/usr/bin/env perl
use 5.010;
use strict;
use warnings;
use Thread qw(async);
async {
my @messages = qw(Hoge Fuga Hago);
my $interval = 3;
while () {
foreach my $v (@messages) {
say $v;
sleep $interval;
}
}
};
print while (<>);
Start-Job {
$messages = ('Hoge', 'Fuga', 'Hago')
$interval = 3
while (1) {
foreach ($v in $messages) {
$v | Out-File $HOME\messages.txt -append
sleep $interval
}
}
}
while (1) {
Read-Host | Out-Host
}
#!/usr/bin/env python
import threading
import time
def loop():
messages = ['Hoge', 'Fuga', 'Hago']
interval = 3
while True:
for v in messages:
print v
time.sleep(interval)
t = threading.Thread(target=loop)
t.setDaemon(True)
t.start()
while True:
print raw_input()
#!/usr/bin/env ruby
Thread.start do
messages = %w[Hoge Fuga Hago]
interval = 3
loop do
messages.each do |v|
puts v
sleep interval;
end
end
end
puts $_ while gets
import scala.concurrent.ops._
import java.lang.Thread._
spawn {
val messages = List("Hoge", "Fuga", "Hago")
val interval = 3000
while (true) {
for (v <- messages) {
println(v)
sleep(interval)
}
}
}
do println(readLine) while (true)
#!/bin/bash
LOOP=`cat << 'EOL'
MESSAGES=(Hoge Fuga Hago)
INTERVAL=3
while :; do
for v in ${MESSAGES[@]}; do
PARENT=\`pgrep -P $PPID\`
if [ ! "$PARENT" ]; then
exit 9
fi
echo $v
sleep $INTERVAL
done
done
EOL`
bash -c "$LOOP" &
while read INPUT; do
echo $INPUT
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment