标签: callable

我如何包装一个方法,以便在超过指定的超时时可以终止它的执行?

我有一个方法,我想打电话.但是,我正在寻找一种干净,简单的方法来杀死它或强迫它返回,如果执行时间太长.

我正在使用Java.

为了显示:

logger.info("sequentially executing all batches...");
for (TestExecutor executor : builder.getExecutors()) {
logger.info("executing batch...");
executor.execute();
}
Run Code Online (Sandbox Code Playgroud)

我认为TestExecutor班级应该implement Callable继续向这个方向发展.

但我想要做的就是停止,executor.execute()如果它花了太长时间.

建议...?

编辑

收到的许多建议都假设正在执行的方法需要很长时间才能包含某种循环,并且可以定期检查变量.然而,这种情况并非如此.因此,某些东西不一定是干净的,只会停止执行,这是可以接受的.

java concurrency multithreading callable

15
推荐指数
3
解决办法
8379
查看次数

RestTemplate应该是全局声明的静态吗?

我在我的代码中使用Java Callable Future.下面是我使用未来和callables的主要代码 -

public class TimeoutThread {

    public static void main(String[] args) throws Exception {

        ExecutorService executor = Executors.newFixedThreadPool(5);
        Future<String> future = executor.submit(new Task());

        try {
            System.out.println("Started..");
            System.out.println(future.get(3, TimeUnit.SECONDS));
            System.out.println("Finished!");
        } catch (TimeoutException e) {
            System.out.println("Terminated!");
        }

        executor.shutdownNow();
    }
}
Run Code Online (Sandbox Code Playgroud)

下面是我的Task类,它实现了Callable接口,我需要根据我们拥有的主机名生成URL,然后使用调用SERVERS RestTemplate.如果第一个主机名中有任何异常,那么我将为另一个主机名生成URL,我将尝试拨打电话.

class Task implements Callable<String> {
    private static RestTemplate restTemplate = new RestTemplate();

    @Override
    public String call() throws Exception {

    //.. some code

    for(String hostname : hostnames)  {
            if(hostname == null) {
                continue;
            }
            try …
Run Code Online (Sandbox Code Playgroud)

java multithreading callable resttemplate

15
推荐指数
1
解决办法
1万
查看次数

发电机是否可以调用?哪个是发电机?

生成器只是一个函数,它返回一个可以在其上调用的对象,这样每次调用它都会返回一些值,直到它引发一个StopIteration异常,表示已生成所有值.这样的对象称为迭代器.

>>> def myGen(n):
...     yield n
...     yield n + 1
... 
>>> g = myGen(6)
Run Code Online (Sandbox Code Playgroud)

我从Python中理解生成器中引用了这个

这是我想弄清楚的:

  1. 哪个是发电机?myGen还是myGen(6)

    根据上面提到的报价,我认为发电机应该是myGen.并且myGen(6)是返回的迭代器对象.但我真的不确定.

  2. 当我尝试这个时:

    >>> type(myGen)
    <type 'function'>
    >>> type(g)         # <1>this is confusing me.
    <type 'generator'>  
    >>> callable(g)     # <2> g is not callable.  
    False               
    >>> callable(myGen)
    True
    >>> g is iter(g)    # <3> so g should an iterable and an iterator 
    True                # at the same time. And it …
    Run Code Online (Sandbox Code Playgroud)

python generator callable

14
推荐指数
1
解决办法
3152
查看次数

在Python中动态分配函数实现

我想动态分配一个函数实现.

让我们从以下开始:

class Doer(object):

    def __init__(self):
        self.name = "Bob"

    def doSomething(self):
        print "%s got it done" % self.name

def doItBetter(self):
    print "Done better"
Run Code Online (Sandbox Code Playgroud)

在其他语言中,我们将使doItBetter成为匿名函数并将其分配给对象.但是不支持Python中的匿名函数.相反,我们将尝试创建一个可调用的类实例,并将其分配给该类:

class Doer(object):

    def __init__(self):
        self.name = "Bob"

class DoItBetter(object):

    def __call__(self):
        print "%s got it done better" % self.name

Doer.doSomething = DoItBetter()
doer = Doer()
doer.doSomething()
Run Code Online (Sandbox Code Playgroud)

这给了我这个:

回溯(最近一次调用最后一次):第13行,在doer.doSomething()第9行,在调用 打印"%s让它做得更好"%self.name AttributeError:'DoItBetter'对象没有属性'name'

最后,我尝试将callable作为属性分配给对象实例并调用它:

class Doer(object):

    def __init__(self):
        self.name = "Bob"

class DoItBetter(object):

    def __call__(self):
        print "%s got it done better" % self.name


doer = Doer()
doer.doSomething = …
Run Code Online (Sandbox Code Playgroud)

python anonymous-methods callable anonymous-function

13
推荐指数
2
解决办法
8417
查看次数

我如何解决这个"TypeError:'str'对象不可调用"错误?

我正在创建一个基本程序,它将使用GUI来获取商品的价格,如果初始价格低于10,则从价格中扣除10%,或者如果初始价格是,则从价格中取20%的折扣大于十:

import easygui
price=easygui.enterbox("What is the price of the item?")
if float(price) < 10:
    easygui.msgbox("Your new price is: $"(float(price) * 0.1))
elif float(price) > 10:
    easygui.msgbox("Your new price is: $"(float(price) * 0.2))
Run Code Online (Sandbox Code Playgroud)

我不断收到此错误:

easygui.msgbox("Your new price is: $"(float(price) * 0.1))
TypeError: 'str' object is not callable`
Run Code Online (Sandbox Code Playgroud)

为什么我收到此错误?

python string comparison user-interface callable

12
推荐指数
1
解决办法
9万
查看次数

为什么我们在python中有可调用的对象?

可调用对象的目的是什么?他们解决了什么问题?

python callable

11
推荐指数
2
解决办法
6306
查看次数

替代callable(),用于Python 3

我查看了这个帖子,但有些概念高于我目前的水平.在Python 2.x中,callable()内置方法存在; 是否有一种简单的方法来检查是否可以使用Python 3调用某些内容?

callable python-3.x

11
推荐指数
3
解决办法
6108
查看次数

JavaScript中可调用对象的构造方法

如何在JavaScript中为可调用对象创建构造函数?

我尝试了各种各样的方式,比如跟随.这个例子只是缩短了实际对象的例子.

function CallablePoint(x, y) {
    function point() {
        // Complex calculations at this point
        return point
    }
    point.x = x
    point.y = y
    return point
}
Run Code Online (Sandbox Code Playgroud)

这工作在第一,但它创建的对象不是实例CallablePoint,因此它不会从复制的属性CallablePoint.prototype,并说falseinstanceof CallablePoint.是否可以为可调用对象创建工作构造函数?

javascript constructor callable

11
推荐指数
1
解决办法
7372
查看次数

可调用<Void>作为lambdas的功能接口

我刚学习新的java8功能.这是我的问题:

为什么不允许将Callable<Void>其用作lambda表达式的功能接口?(编译器抱怨返回值)并且在Callable<Integer>那里使用它仍然是完全合法的.以下是示例代码:

public class Test {
    public static void main(String[] args) throws Exception {
        // works fine
        testInt(() -> {
            System.out.println("From testInt method"); 
            return 1;
        });

        testVoid(() -> {
            System.out.println("From testVoid method"); 
            // error! can't return void?
        });
    }

    public static void testInt(Callable<Integer> callable) throws Exception {
        callable.call();
    }

    public static void testVoid(Callable<Void> callable) throws Exception {
        callable.call();
    }
}
Run Code Online (Sandbox Code Playgroud)

如何解释这种行为?

java lambda callable void java-8

11
推荐指数
1
解决办法
1万
查看次数

单元测试在调试模式下成功,但在正常运行时失败

为什么我的单元测试在调试模式下成功但在正常运行时失败?

public class ExecutorServiceTest extends MockitoTestCase{   
  private int numThreads;
  private ExecutorService pool;
  private volatile boolean interruptedBitSet;

  @Override
  public void setUp() {
    numThreads = 5;
    pool = Executors.newFixedThreadPool(numThreads);
  }

class TaskChecksForInterruptedBit implements Callable<String> {
    @Override
    public String call() throws Exception {
      interruptedBitSet = false;
      while (!Thread.currentThread().isInterrupted()) {
      }
      interruptedBitSet = Thread.currentThread().isInterrupted();
      return "blah";
    }
  }

public void testCancelSetsInterruptedBitInCallable() throws Exception {
    interruptedBitSet = false;
    final Future<String> future = 
        pool.submit(new TaskChecksForInterruptedBit());
    final boolean wasJustCancelled = future.cancel(true);
    assertTrue(wasJustCancelled);

    // Give time for the …
Run Code Online (Sandbox Code Playgroud)

java junit multithreading future callable

10
推荐指数
2
解决办法
8275
查看次数