我是 Kotlin 的新手。我想创建一个简单的计时器来每秒执行fun
。我研究了一些方法并找到了setInterval。但我无法理解如何在代码中实现。我所需要的只是每秒执行println("Hello, world!")
。
答案 0 :(得分:1)
我不知道setInterval(注意它只是JS平台!)但是如果你想打印“Hello world!”每一秒,这是一个解决方案
fun main(args: Array<String>) {
doEverySeconds {
println("Hello world !")
}
}
然后你可以像这样使用它
fun doEveryX(timeInMS : Long, action: () -> Unit) {
thread {
while (true) {
action()
Thread.sleep(timeInMS)
}
}
}
fun main(args: Array<String>) {
doEveryX(1200) {
println("Hello world !")
}
}
或将时间作为参数
class Classify(object):
def __init__(self, features, label)
self.params = dict(max_depth=100,
min_sample_count=1,
use_surrogates=False,
max_categories=5,
calc_var_importance=False,
nactive_vars=0,
max_num_of_tree_in_the_forest=100,
term_crit=(cv2.TERM_CRITERIA_MAX_ITER,100,0.1))
self.le = preprocessing.LabelEncoder()
self.le.fit(label)
leLabels = np.array(self.le.transform(label), dtype=np.float32)
features_train, features_test, labels_train, labels_test = train_test_split(features, leLabels, test_size=0.2, random_state=0)
result = self.trainingForest(features_train, labels_train)
self.crossValidation(result, features_test, labels_test) #####call to manual computation of crossValidation score
def trainingForest(self, features, label):
features = np.array(features, dtype=np.float32)
model = cv2.RTrees()
model.train(features, cv2.CV_ROW_SAMPLE, label, params=self.params)
#### model.save('tree.xml') ###### the cause of the bug
def crossValidation(self, model, features_test, labels_test):
features_test = np.array(features_test, dtype=np.float32)
predictionResult = []
for item in features_test:
res = self.model.predict(item)
predictionResult.append(res)
accuracy = (labels_test == predictionResult).mean()
error = (labels_test != predictionResult).mean()
print("Manual Accuracy Score: %.2f %%" % (accuracy * 100))
print("Error: %.2f %%" % (error * 100))
return
答案 1 :(得分:0)
要添加到user3491043的答案,我还想指出您可以使用协程或 Java的Timer#scheduleAtFixedRate
。
以下是使用协同程序的示例:
async {
while (true) {
// Do whatever
delay(interval)
}
}