scheduledexecutorservice工作不正常

z9zf31ra  于 2021-07-06  发布在  Java
关注(0)|答案(2)|浏览(518)

我使用scheduledexecutorservice每15秒从网站获取一次数据:

  1. ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
  2. scheduler.scheduleAtFixedRate(this::refresh, 0, 15, TimeUnit.SECONDS);

这是每15秒调用一次的方法:

  1. public void refresh() {
  2. Site.refreshData();
  3. System.out.println("Refreshed Data");
  4. LinearLayout listView = findViewById(R.id.linearLayout);
  5. System.out.println("Size: " + List.getList().size());
  6. for (int i = 0; i < List.getList().size(); i++) {
  7. Entry entry = List.getList().get(i);
  8. CardView cardView = (CardView) LayoutInflater.from(
  9. getApplicationContext()).inflate(R.layout.card, listView, false);
  10. ImageView checkedView = (ImageView) cardView.getChildAt(0);
  11. checkedView.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(),
  12. entry.isChecked() ? R.drawable.check : R.drawable.cross));
  13. TextView name = (TextView) cardView.getChildAt(1);
  14. name.setText(entry.getName());
  15. TextView comment = (TextView) cardView.getChildAt(2);
  16. comment.setText(entry.getComment());
  17. listView.addView(cardView, i);
  18. }
  19. System.out.println("Added Cardviews");
  20. listView.invalidate();
  21. System.out.println("Refreshed LinearLayout");
  22. }

我添加了多个打印,作为一个穷人的调试器,我只到了打印arraylist大小的地步。从那以后什么都没有印出来,就好像行刑停止了。我确信错误发生在for循环中。我添加了一个打印,显示当前 i 虽然列表大小是57,但它只停留在4。
有什么问题吗?

5kgi1eie

5kgi1eie1#

经过更多的搜索,我找到了一个方法,它完全符合我的要求:
runonuithread(可运行-可运行)

  1. //scheduler.scheduleAtFixedRate(this::refresh, 0, 15, TimeUnit.SECONDS); ->
  2. public void refresh() {
  3. Site.refreshData();
  4. runOnUiThread(() -> {
  5. ((TextView) findViewById(R.id.queueView)).setText("Total Entries: " + List.getList().size());
  6. LinearLayout listView = findViewById(R.id.linearLayout);
  7. listView.removeAllViews();
  8. for (Entry entry : List.getList()) {
  9. CardView cardView = (CardView) LayoutInflater.from(
  10. getApplicationContext()).inflate(R.layout.card, listView, false);
  11. ImageView checkedView = (ImageView) cardView.getChildAt(0);
  12. checkedView.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(),
  13. entry.isChecked() ? R.drawable.check : R.drawable.cross));
  14. TextView name = (TextView) cardView.getChildAt(1);
  15. name.setText(entry.getName());
  16. TextView comment = (TextView) cardView.getChildAt(2);
  17. comment.setText(entry.getComment());
  18. listView.addView(cardView);
  19. }
  20. Toast.makeText(getApplicationContext(), "Refreshed data and UI.", Toast.LENGTH_SHORT).show();
  21. });
  22. }
展开查看全部
ax6ht2ek

ax6ht2ek2#

在构建gui之前,请在控制台上执行计划的页面检索。
下面是一个示例应用程序。每五秒钟半分钟我们下载一个页面并将其各个部分转储到控制台。
此演示使用 HttpClient 根据jep 321:http客户机添加到java11的类。这里显示的网页访问代码是从本文复制的。
提示:一定要优雅地关闭executor服务,因为它的线程池可能会无限期地继续运行,即使在你的应用程序结束之后。

  1. package work.basil.example;
  2. import java.io.IOException;
  3. import java.net.Authenticator;
  4. import java.net.InetSocketAddress;
  5. import java.net.ProxySelector;
  6. import java.net.URI;
  7. import java.net.http.HttpClient;
  8. import java.net.http.HttpHeaders;
  9. import java.net.http.HttpRequest;
  10. import java.net.http.HttpResponse;
  11. import java.time.Duration;
  12. import java.time.Instant;
  13. import java.util.concurrent.Executors;
  14. import java.util.concurrent.ScheduledExecutorService;
  15. import java.util.concurrent.TimeUnit;
  16. public class PageFetch
  17. {
  18. public static void main ( String[] args )
  19. {
  20. PageFetch app = new PageFetch();
  21. app.demo();
  22. }
  23. private void demo ( )
  24. {
  25. Runnable pageFetchRunnable = ( ) -> { this.fetchPage(); };
  26. ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
  27. scheduledExecutorService.scheduleAtFixedRate( pageFetchRunnable , 1 , 5 , TimeUnit.SECONDS ); // Wait one second, then every five seconds.
  28. try
  29. {
  30. Thread.sleep( Duration.ofSeconds( 30 ).toMillis() ); // Let the executor service do its thing for a half-minute, then shut it down.
  31. }
  32. catch ( InterruptedException e )
  33. {
  34. e.printStackTrace();
  35. }
  36. finally
  37. {
  38. scheduledExecutorService.shutdown();
  39. }
  40. }
  41. private void fetchPage ( )
  42. {
  43. // Example code for using `HttpClient` framework of Java 11 taken from this article:
  44. // https://mkyong.com/java/java-11-httpclient-examples/
  45. HttpClient httpClient = HttpClient.newBuilder()
  46. .version( HttpClient.Version.HTTP_2 )
  47. .followRedirects( HttpClient.Redirect.NORMAL )
  48. .connectTimeout( Duration.ofSeconds( 20 ) )
  49. // .proxy( ProxySelector.of(new InetSocketAddress("proxy.yourcompany.com", 80)))
  50. // .authenticator( Authenticator.getDefault())
  51. .build();
  52. HttpRequest request = HttpRequest.newBuilder()
  53. .GET()
  54. .uri( URI.create( "https://httpbin.org/get" ) )
  55. .setHeader( "User-Agent" , "Java 11 HttpClient Bot" ) // add request header
  56. .build();
  57. HttpResponse < String > response = null;
  58. try
  59. {
  60. System.out.println( "\n-----| Demo |-------------------------------------------" );
  61. System.out.println( "INFO - Access attempt at " + Instant.now() );
  62. response = httpClient.send( request , HttpResponse.BodyHandlers.ofString() );
  63. // print response headers
  64. HttpHeaders headers = response.headers();
  65. headers.map().forEach( ( k , v ) -> System.out.println( k + ":" + v ) );
  66. // print status code
  67. System.out.println( response.statusCode() );
  68. // print response body
  69. System.out.println( response.body() );
  70. }
  71. catch ( IOException e )
  72. {
  73. e.printStackTrace();
  74. }
  75. catch ( InterruptedException e )
  76. {
  77. e.printStackTrace();
  78. }
  79. }
  80. }

运行时:

  1. -----| Demo |-------------------------------------------
  2. INFO - Access attempt at 2020-11-20T21:54:37.905896Z
  3. :status:[200]
  4. access-control-allow-credentials:[true]
  5. access-control-allow-origin:[*]
  6. content-length:[242]
  7. content-type:[application/json]
  8. date:[Fri, 20 Nov 2020 21:54:38 GMT]
  9. server:[gunicorn/19.9.0]
  10. 200
  11. {
  12. "args": {},
  13. "headers": {
  14. "Host": "httpbin.org",
  15. "User-Agent": "Java 11 HttpClient Bot",
  16. "X-Amzn-Trace-Id": "Root=1-5fb83b1e-7a6acb893aec6fb310984adb"
  17. },
  18. "origin": "76.22.40.96",
  19. "url": "https://httpbin.org/get"
  20. }
  21. -----| Demo |-------------------------------------------
  22. INFO - Access attempt at 2020-11-20T21:54:42.907678Z
  23. :status:[200]
  24. access-control-allow-credentials:[true]
  25. access-control-allow-origin:[*]
  26. content-length:[242]
  27. content-type:[application/json]
  28. date:[Fri, 20 Nov 2020 21:54:43 GMT]
  29. server:[gunicorn/19.9.0]
  30. 200
  31. {
  32. "args": {},
  33. "headers": {
  34. "Host": "httpbin.org",
  35. "User-Agent": "Java 11 HttpClient Bot",
  36. "X-Amzn-Trace-Id": "Root=1-5fb83b23-3dbb566f5d58a8a367e0e528"
  37. },
  38. "origin": "76.22.40.96",
  39. "url": "https://httpbin.org/get"
  40. }
  41. and so on for a half-minute.
展开查看全部

相关问题